在python中,使用相对xpath查找给定tex之后的第一个表

2024-06-25 05:25:34 发布

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

我试图找到一个相对(而不是绝对)Xpath,它允许我在文本“分割时间”之后导入第一个表。这是我的密码:

from lxml import html
import requests

ResultsPage = requests.get('https://www.iaaf.org/competitions/iaaf-world-championships/iaaf-world-championships-london-2017-5151/results/men/10000-metres/final/result')
ResultsTree = html.fromstring(ResultsPage.content)
ResultsTable = ResultsTree.xpath(("""//*[text()[contains(normalize-space(), "SPLIT TIMES")]]"""))

print ResultsTable

我试图找到Xpath,它将在“SPLIT TIMES”表中磨练,该表在这里https://www.iaaf.org/competitions/iaaf-world-championships/iaaf-world-championships-london-2017-5151/results/men/10000-metres/final/result找到,如下图所示。你知道吗

如果Xpath能尽可能多用,我将不胜感激。例如,这个要求可能会改变,所以我会在文本后面找到第一个表,上面写着“10000米男子”(与上面的url相同)。或者,我可能需要找到文本后面的第一个表,该表的内容为'MEDAL table'(不同的url):https://www.iaaf.org/competitions/iaaf-world-championships/iaaf-world-championships-london-2017-5151/medaltable

enter image description here


Tags: httpsorg文本importworldhtmlwwwrequests
2条回答

您的代码有问题,因为您尝试删除的网站使用了一个将拒绝请求的保护(如另一个答案中指出的,标头中缺少用户代理):

The request could not be satisfied. Request blocked. Generated by cloudfront (CloudFront)

我可以通过使用这个库来绕过这个问题:cloudflare-scrape。你知道吗

可以使用pip安装:

pip install cfscrape

下面是一段代码,其中包含一个有效的xpath,用于实现您想要实现的目标,诀窍是使用文档中描述的“following”axe:https://www.w3.org/TR/xpath/#axes。你知道吗

import cfscrape
from lxml import html

scraper = cfscrape.create_scraper()
page = scraper.get('https://www.iaaf.org/competitions/iaaf-world-championships/iaaf-world-championships-london-2017-5151/results/men/10000-metres/final/result')
tree = html.fromstring(page.content)
table = tree.xpath(".//h2[contains(text(), 'Split times')][1]/following::table[1]")

可以通过xpath使用following,如下所示。你知道吗

relative_string = "Split times"

ResultsTable = ResultsTree.xpath("//*[text()[contains(normalize-space(), '"+relative_string+"')]]/following::table")

相关问题 更多 >