scrapy - scrapy 通过 urls'path 将数据导出到文件
问题描述
当我从 HTML 页面导出数据时,如何更改 scrapy 的源代码,以便通过 url 保存文件。
例如:这个页面(http://example/big/ppp
)有很多页面链接
http://example/big/ppp/a
http://example/big/ppp/b
http://example/big/ppp/c
- ……
我想保存数据
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
。
那你能帮帮我吗,好心人!
解决方案
您可以使用 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。
推荐阅读
- javascript - 按下按钮前显示 Highchart + Plotly dash 图表
- python - 使用 python 从 url 读取 json 数据时出现错误“urllib.error.HTTPError: HTTP Error 403: Forbidden”
- django - Debuggin django 登录 NGINX - DigitalOcean
- angular - ngOnInit 上的 await 函数返回未定义
- javascript - React Native - 格式化文本中的链接
- javascript - 在被覆盖的页面上注入时,我的脚本如何在 HTML 模板中工作?(导入 jQuery)
- google-tag-manager - 使用 Google 跟踪代码管理器添加带有 onload 的脚本
- ruby - 你如何运行 Homebrew 内部测试?
- flutter - Flutter中如何在GroupedListView中进行搜索
- python - 如何在 Python 中有效地创建随机动态图?