我正在提取一些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 是否有一些源代码感知的语法?
谢谢
最佳答案
如果您有兴趣让内容在页面上可见,您可以使用:all[5].text
,如下所述:http://lxml.de/api/lxml.etree._Element-class.html#text
如果您需要该元素的实际 html,您可以使用 ElementTree 的 tosstring
方法:
导入 xml.etree.ElementTree 作为 etree
etree.tostring(全部[5])
此外,正如 CristFati 提到的,尽量避免使用 all
作为变量,因为它是一个 Python 内置函数,并且您已经覆盖了它的引用。
https://docs.python.org/3/library/functions.html#all
关于python - 获取源代码行 lxml python 中的所有元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48901338/