Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/287.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 从本地文件解析HTML_Python_Html_Google App Engine_Lxml - Fatal编程技术网

Python 从本地文件解析HTML

Python 从本地文件解析HTML,python,html,google-app-engine,lxml,Python,Html,Google App Engine,Lxml,我正在用Python使用Google应用程序引擎。我想从与Python脚本相同的项目中获取HTML文件的树。我尝试了很多方法,比如使用绝对url(例如)和相对url(/nl/home.html)。两者似乎都不起作用。我使用以下代码: class HomePage(webapp2.RequestHandler): def get(self): path = self.request.path htmlfile = etree.parse(path

我正在用Python使用Google应用程序引擎。我想从与Python脚本相同的项目中获取HTML文件的树。我尝试了很多方法,比如使用绝对url(例如)和相对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

似乎是权限问题;请检查您的python脚本是否可以访问该文件。如果您将该文件提供给所有人,该文件是否有效?

我相信您的错误在文件路径中。您假设您的应用程序目录是服务器上文件系统的根目录。不一定如此。实际上,我找不到任何错误关于文件将在哪里的文档,这就是我要做的(它在dev服务器上工作,我还没有在生产中厌倦它):

我假设Google在我的应用程序中保留了文件的相对位置。因此,如果我知道一个文件的位置,我可以确定其余文件的位置。幸运的是,python规范允许您以编程方式确定python源文件的位置,如下所示:

def get_src_dir(){
    return os.path.dirname(os.path.realpath(__file__))
}
get_src_dir()您将获得源文件的位置

os.path.join(get_src_dir(), rel_path_to_asset)

现在将为您获取资产的路径。rel_path_to_asset是相对于源文件的资产路径,get_src_dir()函数位于…

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

  • app.yaml
  • nl/
    • home.html

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

我在app.yaml文件中添加了以下代码:-url:/nl static\u dir:nl application\u readable:true,但它仍然无法正常工作。有证据表明,工作目录是app目录的基础吗?我找不到关于它的任何具体信息,因此我使用了回答中描述的机制来获得pat我的应用程序文件的h…我找不到正式的文档,但它在页面上作为提示被提到。好的,这是一个好的文档,正如我从谷歌期望的那样(无意冒犯,但说真的,文档怎么会这么差…)。谢谢,这对我帮助很大!最终,我的代码需要做更多的编辑,请参阅我的问题以了解工作代码。