首页 > 解决方案 > scrapy 通过 urls'path 将数据导出到文件

问题描述

当我从 HTML 页面导出数据时,如何更改 scrapy 的源代码,以便通过 url 保存文件。

例如:这个页面(http://example/big/ppp)有很多页面链接

  1. http://example/big/ppp/a
  2. http://example/big/ppp/b
  3. http://example/big/ppp/c
  4. ……

我想保存数据

http://example/big/ppp/a d:/ppp/a.csv

http://example/big/ppp/b d:/ppp/b.csv

http://example/big/ppp/c d:/ppp/c.csv

因为这个 pages( http://example/big/ppp) 有很多类似 http://example/big/ppp/a,的链接http://example/big/ppp/b

那你能帮帮我吗,好心人!

标签: scrapyweb-crawler

解决方案


您可以使用 scrapy 管道来完成这项工作,为您要导出的项目添加一个字段,例如命名为 'source' ( http://example/big/ppp/a) 以记录该项目的来源:

from scrapy import signals
from scrapy.contrib.exporter import CsvItemExporter

class MyCsvPipeline(object):
    def __init__(self):
        self.csvfiles = {}
        self.exporter = {}

    @classmethod
    def from_crawler(cls, crawler):
        pipeline = cls()
        crawler.signals.connect(pipeline.spider_closed, signals.spider_closed)
        return pipeline

    def close_spider(self, spider):
        for e in self.exporter.values():
            e.finish_exporting()
        for f in self.csvfiles.values():
            f.close()

    def process_item(self, item, spider):
        csv = item['source'].split('/')[-1] + '.csv'
        if csv not in self.csvfiles:
            newfile = open('d:/ppp/'+csv, 'wb')
            self.csvfiles[csv] = newfile
            self.exporter[csv] = CsvItemExporter(newfile)
            self.exporter[csv].start_exporting()
        self.exporter[csv].export_item(item)

        return item

在 settings.py 中应用此管道

ITEM_PIPELINES = {
    'xxxx.pipelines.MyCsvPipeline': 300,
}

另一个选项用于scrapy crawl xxx -t csv -o all.csv --loglevel=INFO将所有项目导出到 csv,然后使用另一个脚本根据“源”将其分成小 csv。


推荐阅读