我嘗試抓取這個網站: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 時這不起作用?
uj5u.com熱心網友回復:
在迭代選擇 xpath 后,您必須使用它.//來獲得所需的結果。嘗試如下:
p.xpath(".//span[@class='price']//child::bdi/text()").get()
uj5u.com熱心網友回復:
如果要在已定義的 Web 元素上使用 xpath
然后你可以使用
>>> for p in products:
... p.xpath(".//span[@class='price']//child::bdi/text()").get()
uj5u.com熱心網友回復:
這個 xpath 選擇器也適用于 Chrome。
//span[@]//child::bdi/text()
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/351432.html
