Python爬虫从入门到精通:(28)scrapy数据持久化存储(基于终端指令)_Python涛哥

2023-11-18

scrapy数据持久化存储(基于终端指令):

上节我们爬取到了内容,那么我们怎么做持久化存储呢?

直接在parse方法中进行 with open() as f ?

如果是这样的话,那我们就没必要使用框架了。

scrapy框架中,我们封装好了持久化存储

import scrapy

class DuanziSpider(scrapy.Spider):
    name = 'duanzi'
    # allowed_domains = ['www.xxx.com']
    start_urls = ['https://duanzixing.com/段子/']

    def parse(self, response):
        article_list = response.xpath('/html/body/section/div/div/article')
        for article in article_list:
            title = article.xpath('./header/h2/a/@title').extract_first()
            note = article.xpath('./p[2]/text()').extract_first()

这是我们上节课获取数据的爬虫文件源码,我们该怎样利用框架进行持久化存储titlenote呢?


基于终端指令的持久化存储

  • 这种方法的实现:该种方式只可以将parse方法的返回值存储到本地制定后缀的文本文件中。
  • 执行指令:scrapy crawl spiderName -o filePath

那么我们先创建个列表存储数据,并返回:

def parse(self, response):
    all_data = []
    article_list = response.xpath('/html/body/section/div/div/article')
    for article in article_list:
        title = article.xpath('./header/h2/a/@title').extract_first()
        note = article.xpath('./p[2]/text()').extract_first()
        dic = {
            'title': title,
            'note': note
        }
        all_data.append(dic)
    return all_data

存储只需一条终端指令:

scrapy crawl duanzi -o duanzi.txt

在这里插入图片描述

我们发现报错了!~ 错误解释是 只能保存json、csv等格式文件

那么久来保存下csv格式的

scrapy crawl duanzi -o duanzi.csv

在这里插入图片描述

然后我们就看到保存成功了!.

关注Python涛哥!学习更多Python知识!

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Python爬虫从入门到精通:(28)scrapy数据持久化存储(基于终端指令)_Python涛哥 的相关文章

随机推荐