我正在使用lxml要进行 HTML 屏幕抓取,我需要通过 text()
选择一个元素,类似于 what is done on another question with pure XML ,但是无论发生什么,我都会收到无效谓词错误。我已将其简化为以下示例:
import lxml.html
sample_html = "<div><h2>test string</h2><h2>other string</h2></div>"
sample_tree = lxml.html.fromstring(sample_html)
sample_tree.findall('.//h2[text()="test string"]')
虽然这应该是有效的,但我不断收到错误:
File "<string>", line unknown
SyntaxError: invalid predicate
有关如何在解析 HTML 时正确让 lxml 通过 text()
选择元素的任何提示吗?
最佳答案
表达式本身有效,但您必须使用 .xpath()
方法:
sample_tree.xpath('.//h2[text()="text string"]')
请注意,您也可以使用.
in place of text()
在这种情况下:
.//h2[. = "text string"]
关于python - 使用 text() 时 lxml 谓词无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43958197/