python - Scrapy使用项目并将数据保存在json文件中
问题描述
我想使用scrapy项目并操作数据并将所有内容保存在json文件中(使用像db这样的json文件)。
# Spider Class
class Spider(scrapy.Spider):
name = 'productpage'
start_urls = ['https://www.productpage.com']
def parse(self, response):
for product in response.css('article'):
link = product.css('a::attr(href)').get()
id = link.split('/')[-1]
title = product.css('a > span::attr(content)').get()
product = Product(self.name, id, title, price,'', link)
yield scrapy.Request('{}.json'.format(link), callback=self.parse_product, meta={'product': product})
yield scrapy.Request(url=response.url, callback=self.parse, dont_filter=True)
def parse_product(self, response):
product = response.meta['product']
for size in json.loads(response.body_as_unicode()):
product.size.append(size['name'])
if self.storage.update(product.__dict__):
product.send('url')
# STORAGE CLASS
class Storage:
def __init__(self, name):
self.name = name
self.path = '{}.json'.format(self.name)
self.load() """Load json database"""
def update(self, new_item):
# .... do things and update data ...
return True
# Product Class
class Product:
def __init__(self, name, id, title, size, link):
self.name = name
self.id = id
self.title = title
self.size = []
self.link = link
def send(self, url):
return # send notify...
Spider 类在 的主页中搜索产品start_url
,然后解析产品页面以捕获尺寸。最后它会搜索是否有更新self.storage.update(product.__dict__)
,如果是真的发送通知。
如何在我的代码中实现 Item?我以为我可以将它插入到产品类中,但我不能包含发送方法......
解决方案
你应该定义你想要的项目。yield
解析后。
最后,运行命令:
scrapy crawl [spider] -o xx.json
PS:默认scrapy支持导出json文件。
推荐阅读
- javascript - 检查文件内容的变化
- php - 如何在 Laravel 表单文本输入中添加静态文本?
- c# - 如何在 xaml 中将最后一个列表框项目与其他列表框项目分开
- python - *args 可以在关键字参数之后使用吗
- arrays - 容量何时与数组末尾不同 - 切片开头?
- python - 在另一列上使用 groupBy 为 nan 添加模式值
- r - 计算满足特定标准的独特组合
- javascript - 当引入另一个 ajax 函数时,Ajax 代码不再运行
- php - 如何使用 PHP 在循环中迭代地向远程服务器发送发布请求?
- python-3.x - Python:元素存在于列表 1 和列表 2 中