python绝对XPath返回空列表,泛型查询更好吗?

2024-04-18 17:55:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我希望使用XPath从html页面获取文本。 特定文本位于描述右侧的td中:(在th元素内)来自源中的url。你知道吗

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

我需要一个通用的XPath查询,它将采用一个文本标题(如“Description:”),并在其旁边提供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查询,但我的知识还不够深入。 任何帮助都将不胜感激。你知道吗


Tags: text文本idtreeurl标题htmlpage
1条回答
网友
1楼 · 发布于 2024-04-18 17:55:23

使用//*[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']

相关问题 更多 >