H O*_*H O 3 python xpath scrapy scrapy-spider
我将从尝试用于遍历一系列车辆并提取模型和价格的草率代码开始:
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
Run Code Online (Sandbox Code Playgroud)
我本以为可以遍历清单并仅返回被解析的单个车辆的价格,但是实际上它会将页面上所有价格的数组添加到每个车辆项目中。
我认为问题出在我的xpath选择器中-是否"//div[contains(@class,'price')]/text()"以某种方式允许解析器查看应每次解析的单车外的div?
作为参考,如果我这样做,listings[1]它仅返回1个列表,因此循环应该正常工作。
编辑:我在print vehicle.extract()上面添加了一行,并确认那vehicle肯定只是一个项目(并且每次循环迭代时它都会更改)。应用于车辆的xpath选择器如何能够逃离车辆对象并返回所有价格?
我遇到了同样的问题。我已经查阅了您所参考的文件。在此处提供修改后的代码,以便对像我这样的初学者有所帮助。请注意'.'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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1683 次 |
| 最近记录: |