我正在尝试迭代某个足球队的实际团队成员。我注意到,在维基百科中,属于球队的球员具有相同的格式。在这种格式下有4-6张桌子,其中2张是一线队球员,其余的是租借球员或年轻球员等。当使用在线工具通过XPath查询查询维基百科页面时,我得到了我想要的结果,但是当我在Python lxml.html库和请求库中使用它,而不是将球员表看作4-6个表时,它将其视为一个表元素,这使得只提取一线队球员令人头疼。
下面是我的python代码:
def create_team_ontology(ontology_graph,team_url,team_name):
res = requests.get(team_url)
doc = lxml.html.fromstring(res.content)
print(team_url)
club_players = doc.xpath("//table[3]/tbody//tr[position() > 1]//td[4]//span/a/@href")
for player_suffix_url in club_players:
print(player_suffix_url+'\n')
player_url = wiki_prefix + player_suffix_url
get_player_info(ontology_graph,player_url,team_name)
这是一个阿森纳https://en.wikipedia.org/wiki/Arsenal维基页面的例子。在源文件中,很容易检查每个表是不同的元素。但是我的俱乐部球员列表包含了上面页面中球员类别下的所有球员href。
这是我在web上运行的代码,使用inspect then ctrl+f //table3/tbody//trposition() > 1//td4//span/a/@href
发布于 2020-04-29 08:31:45
您的代码几乎可以正常工作。如果我使用我在另一个主题中发布的XPath:
from lxml import html
import requests
res = requests.get('https://en.wikipedia.org/wiki/Arsenal_F.C.')
doc = html.fromstring(res.content)
club_players = doc.xpath('//span[@id="Players"]/following::table[1]//span[@class="fn"]//@href')
for player_suffix_url in club_players:
print(player_suffix_url+'\n')
你可以得到阿森纳一线队的27名球员的网址。
/wiki/Bernd_Leno
/wiki/H%C3%A9ctor_Beller%C3%ADn
/wiki/Kieran_Tierney
/wiki/Sokratis_Papastathopoulos
/wiki/Dani_Ceballos
...
https://stackoverflow.com/questions/61480589
复制相似问题