Scrapy / xpath 不工作 - 仅适用于 css
Scrapy / xpath not working - only with css
我试着抓取这个网站: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 时这不起作用?
迭代到 select xpath 后,您必须使用 .//
才能获得所需的结果。尝试如下:
p.xpath(".//span[@class='price']//child::bdi/text()").get()
如果您想在已定义的网络元素上使用 xpath
那么你可以使用
for p in products:
p.xpath(".//span[@class='price']//child::bdi/text()").get()
这个 xpath 选择器也适用于 Chrome。
//span[@class="woocommerce-Price-amount amount"]//child::bdi/text()
我试着抓取这个网站: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 时这不起作用?
迭代到 select xpath 后,您必须使用 .//
才能获得所需的结果。尝试如下:
p.xpath(".//span[@class='price']//child::bdi/text()").get()
如果您想在已定义的网络元素上使用 xpath
那么你可以使用
for p in products:
p.xpath(".//span[@class='price']//child::bdi/text()").get()
这个 xpath 选择器也适用于 Chrome。
//span[@class="woocommerce-Price-amount amount"]//child::bdi/text()