[英]How to produce custom JSON output from Scrapy?
我正在開發一個Scrapy腳本,它應該使輸出如下:
{
"state": "FL",
"date": "2017-11-03T14:52:26.007Z",
"games": [
{
"name":"Game1"
},
{
"name":"Game2"
}
]
}
但是對我來說,當我運行scrapy crawl items -o data.json -t json
時,它的生成如下。 state
的重復
[
{"state": "CA", "games": [], "crawlDate": "2014-10-04"},
{"state": "CA", "games": [], "crawlDate": "2014-10-04"},
]
代碼如下:
進口沙皮
items.py
class Item(scrapy.Item):
state = scrapy.Field()
games = scrapy.Field()
在Spider文件中, item
類稱為:
item = Item()
item['state'] = state
item['Date'] = '2014-10-04'
item['games'] = games
我知道這不是完整的代碼,但是應該給出我的想法。
參考 https://stackoverflow.com/a/43698923/8964297
您可以嘗試這樣編寫自己的管道:
將其放入您的pipelines.py
文件中:
import json
class JsonWriterPipeline(object):
def open_spider(self, spider):
self.file = open('scraped_items.json', 'w')
# Your scraped items will be saved in the file 'scraped_items.json'.
# You can change the filename to whatever you want.
self.file.write("[")
def close_spider(self, spider):
self.file.write("]")
self.file.close()
def process_item(self, item, spider):
line = json.dumps(
dict(item),
indent = 4,
sort_keys = True,
separators = (',', ': ')
) + ",\n"
self.file.write(line)
return item
然后修改您的settings.py
以包括以下內容:
ITEM_PIPELINES = {
'YourSpiderName.pipelines.JsonWriterPipeline': 300,
}
將YourSpiderName
更改為您的蜘蛛的正確名稱。
請注意,文件是由管道直接寫入的,因此您不必使用-o
和-t
命令行參數來指定文件和格式。
希望這能使您更接近所需。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.