我尝试抓取此网站:https://www.magnatiles.com/products/page/1/
我用获得所有元素
products = response.xpath("//ul[@class='products']//ancestor::li")
不,我试着找到所有元素的价格在碎屑外壳-一开始我试着:
>>> 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选择进行了尝试,结果成功了:
>>> 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选择器时,为什么这不起作用?
迭代选择xpath后,必须使用.//
才能获得所需的结果。尝试如下:
p.xpath(".//span[@class='price']//child::bdi/text()").get()
如果您想在已经定义的web元素上使用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()