【问题标题】:get all elements in source line lxml python获取源代码行 lxml python 中的所有元素
【发布时间】:2018-02-21 08:38:43
【问题描述】:

我正在提取一些 html 信息并使用 python 中的.xpath 方法对其进行查询。对于一个特定的应用程序,我想提取属于特定源行的所有元素。比如

with open(self.file_path, 'r') as f:
    page = f.read()
tree = html.fromstring(page)
all = tree.xpath(r'/html/body//a')
print(all[5].sourceline)

以上产生的源代码行号为 14,其中包含以下源代码 html。

26) <a name="l26" style="background-color: #ffffff">        subroutine </a><a style="background-color: #ffcccc">AdjustParticleDiscretisation()</a>

然后如何使用源代码而不是传统的 xpath 查询来提取此 html 的所有内容?还是 xpath 有一些可以识别源代码的语法?

谢谢

【问题讨论】:

标签: python html xml xpath lxml


【解决方案1】:

如果您有兴趣在页面上显示内容,可以使用:all[5].text,此处提到:http://lxml.de/api/lxml.etree._Element-class.html#text

如果您需要该元素的实际 html,您可以使用 ElementTree 的 tosstring 方法: import xml.etree.ElementTree as etree etree.tostring(all[5])

另外,正如 CristFati 所提到的,尽量避免使用 all 作为变量,因为它是一个 python 内置函数并且你已经覆盖了它的引用。 https://docs.python.org/3/library/functions.html#all

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-03-14
    • 1970-01-01
    • 2019-03-17
    • 2014-11-28
    • 2015-09-10
    • 2015-12-22
    • 2017-06-10
    • 1970-01-01
    相关资源
    最近更新 更多