无法解析来自“th”标签的数据以及来自不同表的“td”标签

Can't parse data from `th` tag along with `td` tag from different tables

我在 python 中使用 xpath 编写了一个脚本来解析网页中的表格数据。执行后,它能够完美地解析表中的数据。我唯一无法修复的是解析 table header 表示 th 标记。如果我使用 css 选择器做同样的事情,我可以使用 .cssselect("th,td") 但如果是 xpath 我就卡住了。对于如何解析来自 th 标记的数据的任何帮助,我们也将不胜感激。

这是一个脚本,它能够从不同的表中获取除 th 标签内的数据之外的所有内容:

import requests
from lxml.html import fromstring

response = requests.get("https://fantasy.premierleague.com/player-list/")
tree = fromstring(response.text)
for row in tree.xpath("//*[@class='ism-table']//tr"):
    tab_d = row.xpath('.//td/text()')
    print(tab_d)

我不确定我明白你的意思,但如果你想用单个 XPath 获取 thtd 节点,你可以尝试替换

tab_d = row.xpath('.//td/text()')

tab_d = row.xpath('.//*[name()=("th" or "td")]/text()')

改变

.//td/text()

.//*[self::td or self::th]/text()

也包括 th 个元素。

请注意,假设 tdth 都是 tr 上下文节点的直接子节点是合理的,因此您可以将 XPath 进一步简化为:

*[self::td or self::th]/text()