【问题标题】:python absolute XPath returns empty list, generic query better?python绝对XPath返回空列表,通用查询更好吗?
【发布时间】:2016-02-16 01:07:29
【问题描述】:

我希望使用 XPath 从 html 页面获取文本。 特定文本位于源中 url 的 Description: (inside th element) 右侧的 td 中。

在第一次调用(已注释掉)中,我尝试了从 Chrome 检查器获取的 XPath 的绝对路径,但我得到一个空列表。 下一个调用有效并给出标题: “说明:”

我需要一个通用的 XPath 查询,该查询将采用文本标题(如“描述:”)并在其旁边给出 td 的文本值。

url = 'http://datrack.canterbury.nsw.gov.au/cgi/datrack.pl?cmd=download&id=ZiFfLxV6W1xHWBN1UwR5SVVSAV0GXUZUcGFGHhAyTykQAG5CWVcARwM='
page = requests.get(url)
tree = html.fromstring(page.content)

# desc = tree.xpath('//*[@id="documentpreview"]/div[1]/table[1]/tbody/tr[2]/td//text()')

desc = tree.xpath("//text()[contains(., 'Description:')]")

我尝试过各种 XPath 查询,但我的知识还不够深入。 任何帮助将不胜感激。

【问题讨论】:

    标签: python html list xpath


    【解决方案1】:

    使用//*[contains(text(), 'Description:')] 查找文本包含Description: 的标签,并使用following-sibling::td 查找以下兄弟姐妹td 标签:

    In [180]: tree.xpath("//*[contains(text(), 'Description:')]/following-sibling::td/text()")
    Out[180]: ['Convert existing outbuilding into a recreational area with bathroom and kitchenette']
    

    【讨论】:

    • 我测试过,效果很好!感谢您向我指出这个兄弟符号 unutbu。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-06-23
    • 2016-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多