gpt4 book ai didi

python - Scrapy 循环 - xpath 选择器转义它所应用的对象并返回所有记录?

转载 作者:太空宇宙 更新时间:2023-11-03 13:13:18 27 4
gpt4 key购买 nike

我将从尝试使用 scrapy 代码开始遍历车辆集合并提取模型和价格:

    def parse(self, response):
hxs = Selector(response)
split_url = response.url.split("/")
listings = hxs.xpath("//div[contains(@class,'listing-item')]")
for vehicle in listings:
item = Vehicle()
item['make'] = split_url[5]
item['price'] = vehicle.xpath("//div[contains(@class,'price')]/text()").extract()
item['description'] = vehicle.xpath("//div[contains(@class,'title-module')]/h2/a/text()").extract()
yield item

我原以为它会遍历列表并仅返回被解析的单个车辆的价格,但它实际上是将页面上所有价格的数组添加到每个车辆项目。

我认为问题出在我的 xpath 选择器中 - 是 "//div[contains(@class,'price')]/text()" 以某种方式允许解析器查看外部的 div每次都应该解析的单一车辆?

作为引用,如果我执行 listings[1],它只返回 1 个列表,因此循环应该有效。

编辑:我在上面添加了 print vehicle.extract() 行,并确认 vehicle 绝对只是一个项目(并且每次循环迭代时它都会改变).应用于 vehicle 的 xpath 选择器如何能够逃脱 vehicle 对象并返回所有价格?

最佳答案

我遇到了同样的问题。我已经查阅了您提到的文件。这里提供修改后的代码,希望对像我这样的初学者有所帮助。注意xpath中.//div[contains(@class,'title-module')]/h2/a/text()'.'的用法

def parse(self, response):
hxs = Selector(response)
split_url = response.url.split("/")
listings = hxs.xpath("//div[contains(@class,'listing-item')]")
for vehicle in listings:
item = Vehicle()
item['make'] = split_url[5]
item['price'] = vehicle.xpath(".//div[contains(@class,'price')]/text()").extract()
item['description'] = vehicle.xpath(".//div[contains(@class,'title-module')]/h2/a/text()").extract()
yield item

关于python - Scrapy 循环 - xpath 选择器转义它所应用的对象并返回所有记录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37732649/

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