【问题标题】:Stripping of the addiotional items in xpath剥离 xpath 中的附加项目
【发布时间】:2014-04-15 13:50:48
【问题描述】:

我正在尝试从this website 中抓取项目。

项目包括:品牌、型号和价格。由于页面结构的复杂性,spider 使用了 2 个 xpath 选择器。

品牌和型号商品来自一个 xpath,价格来自不同的 xpath。我按照@har07 的建议使用( | ) 运算符。 Xpaths 为每个项目单独测试,它们正在工作并正确提取所需的项目。但是,在加入 2 个 xpath 后,price 项目开始解析其他项目,例如逗号,并且在输出到 csv 时价格与 Brand/Model 项目不匹配。

这是蜘蛛的解析片段的样子:

def parse(self, response):
    sel = Selector(response)
    titles = sel.xpath('//table[@border="0"]//td[@class="compact"] | //table[@border="0"]//td[@class="cl-price-cont"]//span[4]')
    
    items = []
    for t in titles:
        item = AltaItem()
        item["brand"] = t.xpath('div[@class="cl-prod-name"]/a/text()').re('^([\w\-]+)') 
        item["model"] = t.xpath('div[@class="cl-prod-name"]/a/text()').re('\s+(.*)$') 
        item["price"] = t.xpath('text()').extract()

        items.append(item)

    return(items)

这就是 csv 在抓取后的样子:

有什么建议可以解决这个问题吗?

谢谢。

【问题讨论】:

    标签: python regex xpath scrapy


    【解决方案1】:

    基本上,问题是由您的titles xpath 引起的。 xpath 下降得太深,以至于您需要使用连接两个 xpath 才能抓取品牌/型号字段和价格字段。

    titles xpath 修改为单个 xpath 包括品牌/型号和价格的重复元素(以及随后更改品牌、型号和价格 xpath)意味着您不再会在品牌和型号的位置出现不匹配在一个项目中,价格在下一个项目中。

    def parse(self, response):
        sel = Selector(response)
        titles = sel.xpath('//table[@class="table products cl"]//tr[@valign="middle"]')
        items = []
        for t in titles:
            item = AltaItem()
            item["brand"] = t.xpath('td[@class="compact"]/div[@class="cl-prod-name"]/a/text()').re('^([\w\-]+)')
            item["model"] = t.xpath('td[@class="compact"]/div[@class="cl-prod-name"]/a/text()').re('\s+(.*)$')
            item["price"] = t.xpath('td[@class="cl-price-cont"]//span[4]/text()').extract()
            items.append(item)
        return(items)
    

    【讨论】:

      猜你喜欢
      • 2016-09-01
      • 1970-01-01
      • 2016-05-16
      • 1970-01-01
      • 1970-01-01
      • 2016-05-09
      • 1970-01-01
      • 1970-01-01
      • 2016-01-23
      相关资源
      最近更新 更多