我尝试抓取这个网站:https://www.magnatiles.com/products/page/1/
我得到了所有元素:
products = response.xpath("//ul[@class='products']//ancestor::li")
不,我尝试查找 scrapy shell 中所有元素的价格 - 起初我尝试过:
>>> for p in products:
... p.xpath("//span[@class='price']//child::bdi/text()").get()
...
'134.99'
'134.99'
'134.99'
'134.99'
'134.99'
'134.99'
'134.99'
'134.99'
'134.99'
看来我只得到第一个条目,尽管我正在使用循环
然后我尝试使用 css-selecting 并且它有效:
>>> for p in products:
... p.css("span.price bdi::text").get()
...
'134.99'
'49.99'
'39.99'
'39.99'
'39.99'
'129.99'
'24.99'
'49.99'
'119.99'
为什么当我使用 xpath-selector 时这不起作用?
最佳答案
迭代选择 xpath 后,您必须使用 .//
才能获得所需的结果。请尝试如下:
p.xpath(".//span[@class='price']//child::bdi/text()").get()
关于css - Scrapy/xpath 不工作 - 仅适用于 css,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69864359/