python - Scrapy - 使用 JOBDIR 获取重复项

标签 python csv scrapy

Scrapy 的 JOBDIR 设置提供了可恢复的抓取,描述如下:

http://doc.scrapy.org/en/latest/topics/jobs.html

我尝试像这样执行我的抓取命令:

scrapy crawl myspider -o out.csv -t csv -s JOBDIR=./jobs/run-1

当它仍在运行时,我按 CTRL-C 优雅地关闭了它。然后再次触发相同的命令以恢复它。我可以确认它正在从终端输出中恢复抓取:

[myspider] INFO: Resuming crawl (74 requests scheduled)

但是当我查看我的输出 CSV 文件时,我看到有像这样的重复项:

name,email
Alice,alice@example.com
Bob,bob@example.com
...
name,email            <- duplicated header!
Bob,bob@example.com   <- duplicated row!
...

这正常吗?我想知道在同一命令中使用 -o 选项和 JOBDIR 是否可以。如果没有,如何导出已抓取的项目?

顺便说一句,我正在使用 Scrapy 0.22.1。

谢谢!

最佳答案

是的,这是意料之中的。如果你想看看 scrapy 的源代码,尤其是 CsvItemExporter ,您会发现它在停止/恢复 抓取方面是无状态。导出器基本上使用 2 个标志处理 header 。指示它是否完全包含 header 的一个:include_headers_line。第二个:_headers_not_written,防止每次都转储 header ,写入新的抓取项目, session 的第一项除外。然而,每次重新启动爬虫时,这些标志都会被重置,并且导出器似乎没有携带任何关于恢复 session 的信息:

class CsvItemExporter(BaseItemExporter):

    def __init__(self, file, include_headers_line=True, join_multivalued=',', **kwargs):

        ....
        self._headers_not_written = True
        ....

    def export_item(self, item):
        if self._headers_not_written:
            self._headers_not_written = False
            self._write_headers_and_set_fields_to_export(item)

此外,-o 选项仅指示 crawler将抓取的项目转储到指定的输出中:

class Command(ScrapyCommand):

    ....

    def add_options(self, parser):
        ScrapyCommand.add_options(self, parser)
        parser.add_option("-a", dest="spargs", action="append", default=[], metavar="NAME=VALUE", \
            help="set spider argument (may be repeated)")
        parser.add_option("-o", "--output", metavar="FILE", \
            help="dump scraped items into FILE (use - for stdout)")
        parser.add_option("-t", "--output-format", metavar="FORMAT", default="jsonlines", \
            help="format to use for dumping items with -o (default: %default)")

关于python - Scrapy - 使用 JOBDIR 获取重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22231002/

相关文章:

python - 当我按 CSS 类过滤时,为什么 scrapy 和 beautifulsoup 都没有返回任何内容?

csv - awk:如何过滤掉所有条目(16 列)都为 0 的行

Python:csv.Dictreader 列上的额外逗号

python - 设置 Scrapy 框架以在 Python 2.7 上运行

python - 使用多个外键

python - Python 中 CSV 文件的二维字典、列表或数组

python - Scrapy:在 scrapyd 运行多个蜘蛛 - python 逻辑错误

python for循环不返回多个字典

python - 打破pycharm中未处理的异常

python - pip安装getch Python3.5报错