我正在尝试编写一个 Python 代码,该代码将访问维基百科上的皇家马德里页面并打印其球队的名称
我当前的 xpath 查询是:
for t in doc.xpath("//table//table/tr[position() > 1]/td[4]/span//text()"):
#print the player's name here
但这也会打印“租借”表中的球员。
所以我的问题是如何仅选择包含 xpath 查询中的表的第一个表?或者也许还有另一种方法来实现我想要的?
非常感谢。
P.S:该表从维基百科皇马页面查看源代码的第 775 行开始 ( https://en.wikipedia.org/wiki/Real_Madrid_C.F .)。
最佳答案
您可以使用以下 XPath:
(//span[@id='Current_squad']/following::table)[1]
这将仅选择“当前球队”表。
要获取玩家列表,您可以使用以下 XPath:
(//span[@id='Current_squad']/following::table)[1]//span[@class='fn']//text()
关于python - XPath 选择第一个包含表的表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34556021/