6

我正在做一个 RSS 蜘蛛。如果当前项目中没有匹配项,我想继续执行蜘蛛忽略当前节点......到目前为止,我得到了这个:

        if info.startswith('Foo'):
            item['foo'] = info.split(':')[1]
        else:
            return None

(信息是之前从 xpath 中清除的字符串...)

但我得到了这个例外:

    exceptions.TypeError: You cannot return an "NoneType" object from a

蜘蛛

那么我怎样才能忽略这个节点并继续执行呢?

4

2 回答 2

16
parse(response):
    #make some manipulations
    if info.startswith('Foo'):
            item['foo'] = info.split(':')[1]
            return [item]
        else:
            return []

但更好的是不使用返回,使用yield或什么都不做

parse(response):
    #make some manipulations
    if info.startswith('Foo'):
            item['foo'] = info.split(':')[1]
            yield item
        else:
            return
于 2011-02-18T13:32:37.023 回答
3

当我不得不在解析期间跳过该项目但在回调函数之外时,我发现了一个未记录的方法。

只需StopIteration在解析期间的任何地方引发。

class MySpider(Spider):
    def parse(self, response):
        value1 = parse_something1()
        value2 = parse_something1()
        yield Item(value1, value2)

    def parse_something1(self):
        try:
            return get_some_value()
        except Exception:
            self.skip_item()

    def parse_something2(self):
        if something_wrong:
            self.skip_item()

    def skip_item(self):
        raise StopIteration
于 2017-06-11T22:20:01.340 回答