首页 > 解决方案 > 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?我以为我可以将它插入到产品类中,但我不能包含发送方法......

标签: pythonpython-3.xweb-scrapingscrapyscrapy-item

解决方案


你应该定义你想要的项目。yield解析后。

最后,运行命令: scrapy crawl [spider] -o xx.json

PS:默认scrapy支持导出json文件。


推荐阅读