【问题标题】:Double selection from xpath scrapyxpath scrapy的双重选择
【发布时间】:2016-05-02 14:46:36
【问题描述】:

我想使用 xpath 和 scrapy 提取数据。这是我的代码:

def parse(self, response):
        Coords = []
        for sel in response.xpath('//*[@id="pitch"]/image[contains(@class,"success")]'):
            item = PogbaItem()
            item['x'] = sel.xpath('@x').extract()
            item['y'] = sel.xpath('@y').extract()
            item['x'] = sel.xpath('@x1').extract()
            item['y'] = sel.xpath('@y1').extract()
            Coords.append(item)
        return Coords

问题在于 html 包含两个不同的元素:第一个 (image) 具有属性 x,y,另一个 (line) 具有属性 x1,y1。我正在尝试将它们放在一起以获得最终的 csv,但我找不到正确的 xpath 我该如何解决?

更新HTML的两个例子:

<image class="pitch-object timer-1-40 success" x="331.172" y="84.678" width="30" height="30" xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="/sites/fourfourtwo.com/modules/custom/statzone/files/icons/successful_clearance.png"></image>

<line class="pitch-object timer-2-84 success" marker-end="url(#smallblue)" x1="453.076" y1="199.169" x2="509.104" y2="216.676" style="stroke:blue;stroke-width:3"></line>

【问题讨论】:

    标签: xpath scrapy


    【解决方案1】:

    据我了解,您希望将 x 值作为 x 属性(如果存在),否则将 x1 用作 y。以下是我的解决方法:

    item['x'] = sel.xpath('@x').extract_first() or sel.xpath('@x1').extract_first()
    item['y'] = sel.xpath('@y').extract_first() or sel.xpath('@y1').extract_first()
    

    或者,您可以使用纯 XPath 解决方案:

    item['x'] = sel.xpath('(@x|@x1)').extract_first()
    item['y'] = sel.xpath('(@y|@y1)').extract_first()
    

    而且,由于您需要同时处理 lineimage 元素,您应该调整您的主表达式来处理它:

    //*[@id="pitch"]/*[contains(@class,"success")]
    

    或者:

    //*[@id="pitch"]/*[(self::image or self::line) and contains(@class,"success")]
    

    【讨论】:

    • 对不起,我对 html 元素有误。我刚刚更新了我的答案
    • @slash89mf 好的,请查看更新。有帮助吗?
    • 太完美了!谢谢!
    猜你喜欢
    • 1970-01-01
    • 2013-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-23
    • 2016-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多