删除已抓取的空值数据

问题描述 投票:0回答:1

假设我正在抓取数据,并且某些字段被抓取了

""
,这意味着没有价值。

我不想出现带有

""
的行。我该怎么做? 示例:

field1       field2     field3
my place     blurred    trying
house        fan               
door         mouse      hat

我想要的是我的程序不要将整个第二行写入 CSV,因为 field3 是空的。

python scrapy
1个回答
1
投票

您可以按照[scrapy 文档]中的说明编写和配置项目管道,并删除项目并对其值进行测试。

将此添加到您的

pipeline.py
文件中:

from scrapy.exceptions import DropItem

class DropIfEmptyFieldPipeline(object):

    def process_item(self, item, spider):

        # to test if only "job_id" is empty,
        # change to:
        # if not(item["job_id"]):
        if not(all(item.values())):
            raise DropItem()
        else:
            return item

并将其设置在您的

settings.py
中(适应您的项目名称)

ITEM_PIPELINES = [ 'myproject.pipeline.DropIfEmptyFieldPipeline', ]

在OP关于测试“护士”的评论后进行编辑

from scrapy.exceptions import DropItem
import re

class DropIfEmptyFieldPipeline(object):

    # case-insensitive search for string "nurse"
    REGEX_NURSE = re.compile(r'nurse', re.IGNORECASE)

    def process_item(self, item, spider):
        # user .search() and not .match() to test for substring match
        if not(self.REGEX_NURSE.search(item["job_id"])):
            raise DropItem()
        else:
            return item
© www.soinside.com 2019 - 2024. All rights reserved.