jas*_*son 0 python json scrapy
我目前正在使用 Scrapy 从不同网站抓取一些域,我想知道如何将数据保存在本地 json 文件中,格式为列表或字典,其中键为“domain”,域列表为值。
在爬虫文件中,该项是这样的:
item['domain'] = 'xxx'.extract()
yield item
import json
import codecs
class ChinazPipeline(object):
def __init__(self):
self.file = codecs.open('save.json', 'w', encoding='utf-8')
def process_item(self, item, spider):
line = json.dumps(dict(item), ensure_ascii=False) + "\n"
self.file.write(line)
return item
Run Code Online (Sandbox Code Playgroud)
我期望的是:
{"domain": "['google.com', 'cnn.com', 'yahoo.com']"}
Run Code Online (Sandbox Code Playgroud)
或者只是将我爬取的所有域保存为 json 中的列表,两种方式都适合我。
这很简单。Json 是默认的 scrapy 导出器。您可以通过打开 JSON 文件的输出来使用它:
scrapy runspider yourspider.py -o filename.json
Run Code Online (Sandbox Code Playgroud)
Scrapy 会自动根据文件类型确定您要使用的格式。其他选项有.csv和.jsonline。
这是一个简单的方法。否则你可以自己写ItemExporter。查看出口商文件。
注意:
您甚至不需要在蜘蛛启动期间打开文件,scrapy 会自行管理它。只需产生项目,scrapy 就会自动将其写入文件。
Scrapy 最适合one page -> one itemschema。您想要的是提前抓取所有项目,然后将它们导出为单个列表。
因此,您应该有一些变量,例如self.results,在每次调用中附加新域process_item()。然后在蜘蛛关闭事件上导出它。这个信号有捷径。所以你只需添加:
def closed(self, reason):
# write self.results list to JSON file.
Run Code Online (Sandbox Code Playgroud)