python - 将 Scrapy Python 输出写入 JSON 文件
问题描述
我是 Python 和网络抓取的新手。在这个程序中,我想将最终输出(所有 3 个链接的产品名称和价格)写入 JSON 文件。请帮忙!
import scrapy
from time import sleep
import csv, os, json
import random
class spider1(scrapy.Spider):
name = "spider1"
def start_requests(self):
list = [
"https://www. example.com/item1",
"https://www. example.com/item2",
"https://www. example.com/item3"]
for i in list:
yield scrapy.Request(i, callback=self.parse)
sleep(random.randint(0, 5))
def parse(self, response):
product_name = response.css('#pd-h1-cartridge::text')[0].extract()
product_price = response.css(
'.product-price .is-current, .product-price_total .is-current, .product-price_total ins, .product-price ins').css(
'::text')[3].extract()
name = str(product_name).strip()
price = str(product_price).replace('\n', "")
data = {name, price}
yield data
extracted_data = []
while i < len(data):
extracted_data.append()
sleep(5)
f = open('data.json', 'w')
json.dump(extracted_data, f, indent=4)
解决方案
实际上有一个scrapy命令可以做到这一点(Read):
scrapy crawl <spidername> -o <outputname>.<format>
scrapy crawl quotes -o quotes.json
但是由于您要求提供 python 代码,所以我想出了这个:
def parse(self, response):
with open("data_file.json", "w") as filee:
filee.write('[')
for index, quote in enumerate(response.css('div.quote')):
json.dump({
'text': quote.css('span.text::text').extract_first(),
'author': quote.css('.author::text').get(),
'tags': quote.css('.tag::text').getall()
}, filee)
if index < len(response.css('div.quote')) - 1:
filee.write(',')
filee.write(']')
这与 json 文件的 scrapy 输出命令的作用相同。
推荐阅读
- dynamics-crm - Dynamics CRM 2016 本地 API 身份验证
- docker - Docker build 与主机共享数据
- multithreading - 如何使用 Qt 多线程进行并行列表处理?
- python - Python dateparser.parse 仅在使用 AWS EC2 时返回 NoneType 对象(运行 Python 3.7.9)
- javascript - 在 Chrome 中的 console.log 中显示整个 JSON 对象,而不使用 JSON.stringify()
- nlp - IBM Watson NLU:如何通过 API Endpoint 确定剩余积分?
- python - 如何订阅所有 SharePoint 网站中的文档更改
- java - 如何将方法从一层映射/更改/实现到另一层?
- json - 提取子元素并将父字段添加到其中
- javascript - 在我终止应用程序之前无法接收 Firebase 消息