css - Scrapy/xpath 不工作 - 仅适用于 css

标签 css xpath scrapy

我尝试抓取这个网站: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/

相关文章:

带有 cookie 的 jQuery 样式切换器

xml - XPath,获取XML元素中的下一个属性

python - 动态设置scrapy请求回调

SQL 服务器 : XPath to iterate through multiple elements and return values

python - Scrapy 不会抓取所有页面

python - Scrapy 和 xpath 抓取我的网站并导出 URL - 我做错了什么?

css - 嵌入文本和动画 gif 的自动调整背景大小

javascript - 什么是 UI Bootstrap,它的用途是什么?

jquery - 自动完成建议列表错误的 z-index,我该如何更改?

python - 尽管正确(?)xpath,Selenium Webdriver Python 仍找不到元素