一、items保存爬取的文件

items.py

import scrapy

class QuoteItem(scrapy.Item):
# define the fields for your item here like:
# name = scrapy.Field()
text = scrapy.Field()
author = scrapy.Field()
tags = scrapy.Field()

quote.py

# -*- coding: utf-8 -*-
import scrapy
from toscrapy.items import QuoteItem class QuoteSpider(scrapy.Spider):
name = 'quote'
allowed_domains = ['quotes.toscrape.com']
start_urls = ['http://quotes.toscrape.com/']
"""
知识点
1. text()获取标签的text
2. @属性 获取属性的值
3. extract()查找多个 extract_first() 查找一个
4. response.urljoin url拼接
5. scrapy.Request(url=_next, callback=self.parse) 回调
"""
def parse(self, response):
# print(response.text)
quotes = response.xpath('//div[@class="col-md-8"]/div[@class="quote"]')
# print(quotes)''
for quote in quotes:
# print('=' * 20)
# print(quote)
item = QuoteItem()
# extract_first() 查找一个
text = quote.xpath('.//span[@class="text"]/text()').extract_first()
# print(text)
item['text'] = text
author = quote.xpath('.//span/small[@class="author"]/text()').extract_first()
# print(author)
item['author'] = author
# extract()查找多个
tags = quote.xpath('.//div[@class="tags"]/a[@class="tag"]/@href').extract()
item['tags'] = tags
# print(tags)
yield item
# print('>' * 40)
next_url = response.xpath('//div[@class="col-md-8"]/nav/ul[@class="pager"]/li[@class="next"]/a/@href').extract_first()
# print(next_url)
# 拼接url
_next = response.urljoin(next_url)
# print(_next)
# callback 回调函数
yield scrapy.Request(url=_next, callback=self.parse)

或直接yield QuoteItem()

产生文件命令

scrapy crawl quote -o qutoes.json
scrapy crawl quote -o quotes.jsonlines
or
scrapy crawl quote -o quotes.jl
# 每一个item输出一行json

文件类型:qutoes.xml  qutoes.jl  qutoes.csv等

二、piplines

1、核心:

爬虫每执行一次 yield item对象 -> 执行一次pipelines中的process_item方法(通过修改配置文件使pipelines生效) -> 将数据存入数据库或写入文件

2、settings.py

ITEM_PIPELINES = {
# 后面的参数是不同pipelines类的权重值(0-1000),权重值越小越优先
'toscrapy.pipelines.ToscrapyPipeline': 300,
}

配置settings文件是执行pipeline的前提条件

3、pipelines

a、默认

class ToscrapyPipeline(object):

    def process_item(self, item, spider):
"""
:param item: item对象
:param spider: 爬虫对象
:return:
"""
# print('='*20, item)
return item

b、其它方法

开始爬虫时,调用的方法

    def open_spider(self, spider):
"""
开始爬虫,调用
:param spider:
:return:
"""
pass

爬虫结束时,调用的方法

    def close_spider(self, spider):
"""
关闭爬虫,调用
:param spider:
:return:
"""
pass

from_crawler方法

作用:初始化时,实例化pipleline类对象

目的:将数据储存的路径,写到配置文件中

    @classmethod
def from_crawler(cls, crawler):
"""
初始化方法时,创建pipeline类的对象
:param crawler:
:return:
"""
# crawler.settings 获取全部配置文件
path = crawler.settings.get('FILE_PATH')
# 实例化对象
return cls(path)

c、pipeline类方法分析

判断是否有from_crawler方法

有:obj = pipeline类.from_crawler()

无:obj = pipeline类()

当爬虫开始时,执行 open_spider方法

当爬虫yield item对象时, 执行 process_item方法

当爬虫结束时,执行 close_spider方法

d、序列化

pipelines.py

class ToscrapyPipeline(object):

    def __init__(self, path):
self.f = None
self.path = path @classmethod
def from_crawler(cls, crawler):
"""
初始化方法时,创建pipeline类的对象
:param crawler:
:return:
"""
# crawler.settings 获取全部配置文件
path = crawler.settings.get('FILE_PATH')
# 实例化对象
return cls(path) def open_spider(self, spider):
"""
开始爬虫,调用
:param spider:
:return:
"""
self.f = open(file=self.path, mode='a', encoding="utf-8") def process_item(self, item, spider):
"""
爬虫执行yield item对象,调用
:param item: item对象
:param spider: 爬虫对象
:return:
"""
# print('='*20, item)
self.f.write(item['text'] + '\n')
return item def close_spider(self, spider):
"""
爬虫结束,调用
:param spider:
:return:
"""
self.f.close()

4、多个pipeline类

piplines.py文件中可以有多个类,一个把数据保存到数据库,一个把数据保存到文件

a、执行顺序由settings.py的权重值决定,多个pipeline类中方法的执行顺序可以看成有序的异步

file from_crawl
db from_crawl
file open_spider
db open_spider
file process_item
db process_item
file process_item
db process_item
file process_item
db process_item
db close_spider
file close_spider

b、process_item方法中return item的作用

为下一个pipeline类中的process_item方法提供item

1)、没有返回item

下一个类的item是None

# -*- coding: utf-8 -*-

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html class ToscrapyPipeline(object): def __init__(self, path):
self.f = None
self.path = path @classmethod
def from_crawler(cls, crawler):
"""
初始化方法时,创建pipeline类的对象
:param crawler:
:return:
"""
# crawler.settings 获取全部配置文件
path = crawler.settings.get('FILE_PATH')
# 实例化对象
print('file from_crawl')
return cls(path) def open_spider(self, spider):
"""
开始爬虫,调用
:param spider:
:return:
"""
print('file open_spider')
self.f = open(file=self.path, mode='a', encoding="utf-8") def process_item(self, item, spider):
"""
爬虫执行yield item对象,调用
:param item: item对象
:param spider: 爬虫对象
:return:
"""
print('file process_item')
# self.f.write(item['text'] + '\n')
# return item def close_spider(self, spider):
"""
爬虫结束,调用
:param spider:
:return:
"""
print('file close_spider')
self.f.close() class DBPipeline(object): def __init__(self, path):
self.f = None
self.path = path @classmethod
def from_crawler(cls, crawler):
"""
初始化方法时,创建pipeline类的对象
:param crawler:
:return:
"""
# crawler.settings 获取全部配置文件
path = crawler.settings.get('DB_PATH')
# 实例化对象
print('db from_crawl')
return cls(path) def open_spider(self, spider):
"""
开始爬虫,调用
:param spider:
:return:
"""
print('db open_spider')
self.f = open(file=self.path, mode='a', encoding="utf-8") def process_item(self, item, spider):
"""
爬虫执行yield item对象,调用
:param item: item对象
:param spider: 爬虫对象
:return:
"""
print('db process_item value is {}'.format(item))
# self.f.write(item['text'] + '\n')
return item def close_spider(self, spider):
"""
爬虫结束,调用
:param spider:
:return:
"""
print('db close_spider')
self.f.close()

没有返回item

2)、DropItem

不执行后续pipeline类中的process_item方法

导入

from scrapy.exceptions import DropItem
# -*- coding: utf-8 -*-

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html
from scrapy.exceptions import DropItem class ToscrapyPipeline(object): def __init__(self, path):
self.f = None
self.path = path @classmethod
def from_crawler(cls, crawler):
"""
初始化方法时,创建pipeline类的对象
:param crawler:
:return:
"""
# crawler.settings 获取全部配置文件
path = crawler.settings.get('FILE_PATH')
# 实例化对象
print('file from_crawl')
return cls(path) def open_spider(self, spider):
"""
开始爬虫,调用
:param spider:
:return:
"""
print('file open_spider')
self.f = open(file=self.path, mode='a', encoding="utf-8") def process_item(self, item, spider):
"""
爬虫执行yield item对象,调用
:param item: item对象
:param spider: 爬虫对象
:return:
"""
print('file process_item')
# self.f.write(item['text'] + '\n')
# return item
raise DropItem() def close_spider(self, spider):
"""
爬虫结束,调用
:param spider:
:return:
"""
print('file close_spider')
self.f.close() class DBPipeline(object): def __init__(self, path):
self.f = None
self.path = path @classmethod
def from_crawler(cls, crawler):
"""
初始化方法时,创建pipeline类的对象
:param crawler:
:return:
"""
# crawler.settings 获取全部配置文件
path = crawler.settings.get('DB_PATH')
# 实例化对象
print('db from_crawl')
return cls(path) def open_spider(self, spider):
"""
开始爬虫,调用
:param spider:
:return:
"""
print('db open_spider')
self.f = open(file=self.path, mode='a', encoding="utf-8") def process_item(self, item, spider):
"""
爬虫执行yield item对象,调用
:param item: item对象
:param spider: 爬虫对象
:return:
"""
print('db process_item value is {}'.format(item))
# self.f.write(item['text'] + '\n')
return item def close_spider(self, spider):
"""
爬虫结束,调用
:param spider:
:return:
"""
print('db close_spider')
self.f.close()

DropItem

5、spider参数的作用

作用:pipelines.py中的类和方法是所有爬虫共用的

应用场景:如果先让某个方法,只有一个爬虫可以使用,就要用到spider参数

注意:spider参数对应的是爬虫中的name值

    def open_spider(self, spider):
"""
开始爬虫,调用
:param spider:
:return:
"""
#
if spider == 'quote':
print('file open_spider')
self.f = open(file=self.path, mode='a', encoding="utf-8")

持久化到redis可参考

https://www.cnblogs.com/wanglan/p/10826678.html

使用mongodb参考

https://blog.csdn.net/qq_41020281/article/details/79459604

Scrapy持久化(items+pipelines)的更多相关文章

  1. Scrapy持久化存储

    基于终端指令的持久化存储 保证爬虫文件的parse方法中有可迭代类型对象(通常为列表or字典)的返回,该返回值可以通过终端指令的形式写入指定格式的文件中进行持久化操作; 执行输出指定格式进行存储:将爬 ...

  2. Scrapy持久化存储-爬取数据转义

    Scrapy持久化存储 爬虫爬取数据转义问题 使用这种格式,会自动帮我们转义 'insert into wen values(%s,%s)',(item['title'],item['content' ...

  3. cnblogs 博客爬取 + scrapy + 持久化 + 分布式

    目录 普通 scrapy 分布式爬取 cnblogs_spider.py 普通 scrapy # -*- coding: utf-8 -*- import scrapy from ..items im ...

  4. scrapy持久化到Excel表格

    前提条件: 防止乱码产生 ITEM_PIPELINES = { 'xpc.pipelines.ExcelPipeline': 300, } 方法一 1.安装openpyxl conda install ...

  5. scrapy的使用-Pipelines

    #------------------简单的对item操作方式----------------------------# import json class QsbkPipeline(object): ...

  6. scrapy的持久化相关

    终端指令的持久化存储 保证爬虫文件的parse方法中有可迭代类型对象(通常为列表or字典)的返回,该返回值可以通过终端指令的形式写入指定格式的文件中进行持久化操作. 需求是:将糗百首页中段子的内容和标 ...

  7. scrapy 爬虫框架之持久化存储

    scrapy  持久化存储 一.主要过程: 以爬取校花网为例 : http://www.xiaohuar.com/hua/ 1.  spider    回调函数     返回item 时    要用y ...

  8. scrapy框架的持久化存储

    一 . 基于终端指令的持久化存储 保证爬虫文件的parse方法中有可迭代类型对象(通常为列表or字典)的返回,该返回值可以通过终端指令的形式写入指定格式的文件中进行持久化操作. 执行输出指定格式进行存 ...

  9. (六--二)scrapy框架之持久化操作

    scrapy框架之持久化操作 基于终端指令的持久化存储 基于管道的持久化存储 1 基于终端指令的持久化存储 保证爬虫文件的parse方法中有可迭代类型对象(通常为列表or字典)的返回,该返回值可以通过 ...

随机推荐

  1. activeMQ的两个默认端口8161和61616的区别

    activeMQ默认配置下启动会启动8161和61616两个端口,其中8161是mq自带的管理后台的端口,61616是mq服务默认端口 . 8161是后台管理系统,61616是给java用的tcp端口 ...

  2. linux tasklet工作队列

    工作队列是, 表面上看, 类似于 taskets; 它们允许内核代码来请求在将来某个时间调用 一个函数. 但是, 有几个显著的不同在这 2 个之间, 包括: tasklet 在软件中断上下文中运行的结 ...

  3. Linux 内核USB 接口配置

    USB 接口是自己被捆绑到配置的. 一个 USB 设备可有多个配置并且可能在它们之间转换 以便改变设备的状态. 例如, 一些允许固件被下载到它们的设备包含多个配置来实现这个. 一个配置只能在一个时间点 ...

  4. Comet OJ - Contest #5

    Comet OJ - Contest #5 总有一天,我会拿掉给\(dyj\)的小裙子的. A 显然 \(ans = min(cnt_1/3,cnt_4/2,cnt5)\) B 我们可以感性理解一下, ...

  5. 【Linux】Ubuntu16.04 ftp匿名访问

    一.安装: 1.安装命令: sudo apt-get install vsftpd 2.配置文件: vi /etc/vsftpd.conf 3.开启.关闭.重启服务 sudo /etc/init.d/ ...

  6. linux查看文件内容跳到文件底部和回到文件顶部的快捷键

    有时候需要查看一些日志文件,然后要从底部开始查看的话 可以按 shift+g  即可跳到文件底部 要返回文件顶部的时候 按 gg即可

  7. pytorch代码调试工具

    https://github.com/zasdfgbnm/TorchSnooper pip install torchsnooper 在函数前加装饰器@torchsnooper.snoop()

  8. net core天马行空系列:SummerBoot,将SpringBoot的先进理念与C#的简洁优雅合二为一

    系列目录 1.net core天马行空系列:原生DI+AOP实现spring boot注解式编程 2.net core天马行空系列: 泛型仓储和声明式事物实现最优雅的crud操作 3.net core ...

  9. windows7下mysql8.0.18部署安装

    一.前期准备(windows7+mysql-8.0.18-winx64) 1.下载地址:https://dev.mysql.com/downloads/ 2.选择直接下载不登录账号,下载的压缩包大概两 ...

  10. mysql主丛之基于binlog的不停业务配置主从

    一 环境准备 主:192.168.132.121 从:192.168.132.122 主的数据库上面已经有数据,而且还在不断的写入 mysql> select * from darren.tes ...