gpt4 book ai didi

python - Scrapy 选择器返回页面上的所有内容而不是相对的

转载 作者:太空宇宙 更新时间:2023-11-04 05:49:07 25 4
gpt4 key购买 nike

我正在使用 Scrapy 来抓取一个包含元素列表的网站。但是,当遍历元素列表时,请求相对 xpath 会返回整个页面的所有匹配元素。我一直在使用 0.24,但是升级到最新的 (1.0) 遇到了同样的问题。

我曾尝试使用 virtualenv 运行它以避免与我系统上的其他库发生冲突,但没有成功。

for sel in response.xpath('//ul[@class="items"]//div[@class="item"]'):
item = CrawledItem()
item['id'] = sel.xpath('.//input[@name="id"]/@value').extract()

我已经尝试使用 scrapy parse 进行调试,并注意到 ID 列表从所有匹配项开始,然后慢慢减少,所以到最后一项它只匹配一个 ID。我原以为每个元素只有一个 ID,但我收到的响应类似于以下内容。

[
{
'id': [1,2,3,4,5,6,7,8,9,10]
},
{
'id': [1,2,3,4,5,6,7,8,9]
},
[..] // omitted
{
'id': [10]
}
]

我也尝试过使用 css 选择器但没有成功。我的理解是 .// 用于执行此操作。我怎样才能确保我只是在相对于当前选择器进行选择?

最佳答案

How can I make sure that I'm ONLY selecting relative to the current selector?

明智地选择你的选择器 ;-)

确实,该页面的行为违反直觉,相对选择似乎不起作用。据我检查,您可以使用以下使用更深嵌套选择器的代码获取 productId:

from scrapy import Spider

class TestSpider(Spider):

name= 'test_spider'
start_urls = ['http://www.sainsburys.co.uk/shop/gb/groceries/meat-fish/ham-82654-44']

def parse(self, response):

# print response.body

xpath_products = '//div[@class="addToTrolleyForm "]'

for sel in response.xpath(xpath_products):
src = sel.xpath('.//input[@name="productId"]/@value').extract()
print src

虽然没有为您的问题提供解决方案 - 抱歉,我建议您仔细检查 response.body。

关于python - Scrapy 选择器返回页面上的所有内容而不是相对的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31050285/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com