【问题标题】:Scrapy loop - xpath selector escaping object it is applied to and returning all records?Scrapy 循环 - xpath 选择器转义它所应用的对象并返回所有记录?
【发布时间】:2016-06-09 17:31:07
【问题描述】:

我将从我试图用来遍历车辆集合并提取模型和价格的 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 绝对只是一个项目(每次循环迭代时都会更改)。应用于车辆的 xpath 选择器如何能够逃脱车辆对象并返回所有价格?

【问题讨论】:

    标签: python xpath scrapy scrapy-spider


    【解决方案1】:

    我遇到了同样的问题。我已经查阅了你提到的文件。在此处提供修改后的代码,以便对像我这样的初学者有所帮助。注意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
    

    【讨论】:

      【解决方案2】:

      借助手册here,我能够解决问题。综上所述,xpath 确实在逃避迭代,因为我忽略了在 // 前面加上一个句点,这意味着它每次都在逃避到根节点。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-09-12
        • 2020-12-10
        • 2019-01-07
        相关资源
        最近更新 更多