1、基于终端命令存储
1、基于终端的持久化存储:只可以将parse方法里的返回值存储到本地文件中。
2、持久化存储的文件类型只可为:json、jsonlines、jl、csv、xml
3、操作: scrapy crawl xxx -o filePath
4、优缺点:局限性强,只能存储上述的文件类型,但方便简洁。
2、基于管道存储
1、定义属性
在item类中定义相关属性,
2、封装对象
讲解析到的数据封装存储到item类型的对象中
3、提交item对象
将item类型的对象提交给管道进行持久化存储
上图的
yield item
4、持久化存储操作
在管道文件中的process_item中将接收到的item对象中存储的数据进行持久化存储操作。(存储在mysql中)
# 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
import pymysql
# useful for handling different item types with a single interface
from itemadapter import ItemAdapter
class QiushibaikePipeline:
fp = None
# 重写父类方法,该方法只会被调用一次
def open_spider(self, spider):
print("Begin......")
self.fp = open("./qiushi.txt", 'w', encoding='utf-8')
# 用于处理item对象
# 用来接收爬虫文件提交的item对象
def process_item(self, item, spider):
author = item['author']
content = item['content']
self.fp.write(author + ":" + content + "\n")
return item
def close_spider(self, spider):
print("End......")
self.fp.close()
class mysqlPipeline(object):
conn = None
cursor = None
def open_spider(self, spider):
self.conn = pymysql.Connect(host='localhost', user='root', password='123456', port=3306, db="qiushibaike", charset='utf8')
def process_item(self, item, spider):
self.cursor =self.conn.cursor()
try:
self.cursor.execute('insert into qiushibaike values("%s","%s")'%(item['author'], item['content']))
self.conn.commit()
except Exception as e:
print(e)
self.conn.rollback()
return item
def close_spider(self, spider):
self.cursor.close()
self.conn.close()
要先建立好对应的数据库数据表
可以使用终端命令
mysql-uroot -p
开启数据库,然后输入密码,在输入
creata database 数据库名
创建好数据库后,转入这个数据库
use 数据库名
创建表单
create table 表单名(类型)
然后exit退出
5、配置文件
只有在配置中写入的管道类,该类才会执行,对应的后面数值表示的是执行顺序。
要注意的是:爬虫文件提交的item只会给管道中的第一个被执行的管道类接收,如果有若干个管道类的话,就要在被传入的管道类里在传出item类型。
return item
为了编写方便,建议在每一个管道类中都返回一次item,以便在之后修改代码时提供便利。