我希望使用 XPath 从 html 页面获取文本。 特定文本位于源 URL 中“描述:”(第元素内)右侧的 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 查询的变体,但我的知识不够深入。 任何帮助将不胜感激。
最佳答案
使用//*[contains(text(), 'Description:')]
查找文本包含Description:
的标签,并使用以下- 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']
关于python绝对XPath返回空列表,通用查询更好吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35421940/