gpt4 book ai didi

python - 从本地文件解析 HTML

转载 作者:可可西里 更新时间:2023-11-01 13:31:00 24 4
gpt4 key购买 nike

我正在使用带有 Python 的 Google App Engine。我想从与我的 Python 脚本相同的项目中获取 HTML 文件的树。我尝试了很多东西,比如使用绝对 URL(例如 http://localhost:8080/nl/home.html)和相对 URL(/nl/home.html)。两者似乎都不起作用。我使用这段代码:

class HomePage(webapp2.RequestHandler):    
def get(self):

path = self.request.path

htmlfile = etree.parse(path)
template = jinja_environment.get_template('/nl/template.html')

pagetitle = htmlfile.find(".//title").text
body = htmlfile.get_element_by_id("body").toString()

它返回以下错误:IOError:读取文件“/nl/home.html”时出错:无法加载外部实体“/nl/home.html

有谁知道如何使用 Python 从同一个项目中获取 HTML 文件的树?

编辑

这是工作代码:

class HomePage(webapp2.RequestHandler):    
def get(self):

path = self.request.path.replace("/","",1)
logging.info(path)

htmlfile = html.fromstring(urllib.urlopen(path).read())
template = jinja_environment.get_template('/nl/template.html')

pagetitle = htmlfile.find(".//title").text
body = innerHTML(htmlfile.get_element_by_id("body"))

def innerHTML(node):
buildString = ''
for child in node:
buildString += html.tostring(child)
return buildString

最佳答案

您的工作目录是您应用程序目录的基础。因此,如果您的应用组织如下:

  • 应用.yaml
  • 荷兰/
    • home.html

然后您可以在 nl/html.html 阅读您的文件(假设您没有更改您的工作目录)。

关于python - 从本地文件解析 HTML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30061077/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com