如何使用scrapy中的add_xpath检查未找到的值并将项目值设置为默认值? [英] How to check for unfound value with add_xpath in scrapy and set item value to a default value?

查看:55
本文介绍了如何使用scrapy中的add_xpath检查未找到的值并将项目值设置为默认值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有这个代码:

def parse(self, response)
    l = ItemLoader(item=MyItem(), response=response
    l.add_xpath('title', '//*[@id="title"]/text()', MapCompose(str.strip, str.title)
    l.add_xpath('price', '//*[@id="price"]/text()', MapCompose(lambda i: i.replace(',', ''), float), re = '[,.0-9]')

    return l.load_item()

我想检查是否没有找到元素,在这种情况下,使用 l.add_value 设置一个默认值,例如(我尝试这样做):

I want to check if no element found, in that case set a default value with l.add_value, for example (I tried doing this):

    if l.add_xpath('price', '//*[@id="price"]/text()', MapCompose(lambda i: i.replace(',', ''), float), re = '[,.0-9]'):
        l.add_value('available', 1)
    else:
        l.add_value('price', 0)
        l.add_value('available', 0)

但我得到了奇怪的结果(请参阅此处的讨论).
有什么想法可以实现吗?

But I got odd results (see discussion here).
Any ideas to achieve that?

提前致谢.

推荐答案

ItemLoader 的来源是 这里.add_xpath 方法不返回任何内容(因此默认情况下它返回 None,因此您的 if 语句将始终为 False).

The source for ItemLoader is here. The add_xpath method doesn't return anything (and so by default it returns None, so your if statement will always be False).

似乎确实有一个 get_xpath 方法可以执行您想要的操作(检查元素是否存在).

There does appear to be a get_xpath method that would appear to do what you want (check if the element exists).

这篇关于如何使用scrapy中的add_xpath检查未找到的值并将项目值设置为默认值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆