【问题标题】:lxml invalid predicate when using text()使用 text() 时 lxml 无效谓词
【发布时间】:2017-10-12 23:33:33
【问题描述】:

我正在使用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() 选择元素的任何提示?

【问题讨论】:

    标签: python html lxml


    【解决方案1】:

    表达式本身是有效的,但你必须改用.xpath() 方法:

    sample_tree.xpath('.//h2[text()="text string"]')
    

    请注意,在这种情况下您也可以使用. in place of text()

    .//h2[. = "text string"]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-02-03
      • 1970-01-01
      • 1970-01-01
      • 2016-07-26
      • 1970-01-01
      • 1970-01-01
      • 2016-02-23
      相关资源
      最近更新 更多