刮擦的 xpath 选择器不检索元素



从这个url: https://www.basketball-reference.com/boxscores/202110190LAL.html中,我想从这个xpath中提取文本:

//div[@id='div_four_factors']/table/tbody/tr[1]/td[1]

但是,我得到的元素是None。在Scrapy shell中,我使用这个:

>>> text = response.xpath("//div[@id='div_four_factors']/table/tbody/tr[1]/td[1]/text()").get()
>>> print(text)
>>> None

我已经尝试为我想要检索的元素编写正确的xpath,但没有得到任何结果。

这是因为这个表,它看起来像所有的表从页面已经加载后使用javascript加载。所以在你解析的响应html中不存在xpath路径。

你可以看到如果你打开网页在浏览器中,右键单击并选择"打开页面源代码"或者类似的东西。或者,你可以只使用print(response.text),但它不会被格式化,很难阅读。

然而,它看起来像一个表html的副本被注释掉相邻的位置,当呈现。这意味着你可以这样做:

In [1]: import re
In [2]: pat = re.compile(r'<!--(.*?)-->', flags=re.DOTALL)
In [3]: text = response.xpath("//div[@id='all_four_factors']//comment()").get()
In [4]: selector = scrapy.Selector(text=pat.findall(text)[0])
In [5]: result = selector.xpath('//tbody/tr[1]/td[1]')
In [6]: result
Out[6]: [<Selector xpath='//tbody/tr[1]/td[1]' data='<td class="right " data-stat="pace">1...'>]
In [7]: result[0].xpath('./text()').get()
Out[7]: '112.8'
In [8]: 

最新更新