python scrapy框架 保存数据 .json.csv .txt.xlsx数据库pymysql, pymongo 下载图片与文件

xiaoxiao2021-02-28  58

整理笔记如下:

一 保存为 .json类型

在pipelines.py中:

import json class JsonPipeline(object): def __init__(self):          # 保存的文件         self.file = open('novel.json', 'wb') def process_item(self, item, spider): line = json.dumps(dict(item)) + "\n" self.file.write(line.encode('utf-8')) # 返回 爬虫数据 在items.py中的数据         return item

配置settings.py文件:

# 放开配置 ITEM_PIPELINES = { # Qishu创建的项目名     'Qishu.pipelines.JsonPipeline': 300, }

二 用命令行保存为.json/ .csv类型

# 第一个novel是爬虫文件名即novel.py(在spiders文件中) # 第二个是保存的文件名 scrapy crawl novel -o novel.json -s FEED_EXPORT_ENCODING=utf-8 scrapy crawl novel -o novel.csv-s FEED_EXPORT_ENCODING=utf-8

三 保存为.txt类型

在pipelines.py中:

# 2. 保存伯乐在线所有最新文章:http://blog.jobbole.com/all-posts/ class BolePipeline(object): def __init__(self): self.file = open('bole.txt', 'a', encoding='utf-8') def process_item(self, item, spider): self.file.write('=================================================') self.file.write('\n') self.file.write(item['title']) self.file.write('\n') self.file.write(item['time']) self.file.write(item['cate']) self.file.write('\n') self.file.write(item['content']) self.file.write('\n') self.file.write(item['praise']) self.file.write(item['collect']) self.file.write(item['comment']) self.file.write('\n') return item

配置settings.py文件:

ITEM_PIPELINES = { 'Bole.pipelines.BolePipeline': 300, }

四 保存为xlsx.类型

在pipelines.py中:

# 爬取51Job时的数据 class JobPipeline(object): wb = Workbook() ws = wb.active # 设置表头 ws.append(['职位', '地址', '薪资', '公司', '类型', '经验', '保险', '岗位职责']) def process_item(self, item, spider): # 添加数据 line = [item['job'], item['address'], item['pay'], item['company'], item['type'], item['requests'], item['insures'], item['pmcs']] self.ws.append(line) # 按行添加 self.wb.save('51job.xlsx') return item

配置settings.py文件:

ITEM_PIPELINES = { 'Job.pipelines.JobPipeline': 300, }

五 保存为数据库pymongo

官方文档上也有

https://doc.scrapy.org/en/latest/topics/item-pipeline.html

在pipelines.py中:

import pymongo class MongoPipeline(object): def __init__(self, client, db): self.client = pymongo.MongoClient(client) self.db = self.client[db] # from_crawler()作用就是从settings.py中读取相关配置,然后可以将读取结果保存在类中使用。 @classmethod def from_crawler(cls, crawler): # 创建当前类的对象,并传递两个参数。 obj = cls( client=crawler.settings.get('MONGOCLIENT', 'localhost'), db=crawler.settings.get('DB', 'bole') ) return obj def process_item(self, item, spider): self.db['article'].update_one({'title': item['title']}, {'$set': dict(item)}, True) return item

配置settings.py文件:

# 创建的参数 MONGOCLIENT = 'localhost' DB = 'bole' ITEM_PIPELINES = { 'Bole.pipelines.MongoPipeline': 301, }

六 保存为数据库pymysql

在pipelines.py中:

import pymysql class MysqlPipeline(object): def __init__(self, host, db, user, passwd): # 连接数据库 self.connect = pymysql.connect( host=host, db=db, user=user, passwd=passwd, charset='utf8', use_unicode=True ) # 通过cursor执行增删改查 self.cursor = self.connect.cursor() # from_crawler(): 从setting.py中读取相关配置, 然后可以将读取结果保存在类中使用 @classmethod def from_crawler(cls, crawler): # 创建当前类的对象. 需传递setting中的四个参数 object = cls( host=crawler.settings.get('MYSQL_HOST', 'localhost'), user=crawler.settings.get('MYSQL_USER', 'root'), passwd=crawler.settings.get('MYSQL_PASSWD', '123456'), db=crawler.settings.get('MYSQL_DBNAME', 'bole') ) return object def process_item(self, item, spider): try:              # sql语句              self.cursor.execute( "INSERT INTO article(title, time, cate, content, praise, collect, comment)VALUES (%s, %s, %s, %s, %s, %s, %s)", (item['title'], item['time'], item['cate'], item['content'], item['praise'], item['collect'], item['comment']) ) self.connect.commit() except Exception as e: print('存入数据失败 ', e) return item

配置settings.py文件:

# MySQL ITEM_PIPELINES = { 'Bole.pipelines.MysqlPipeline': 302, } #设置参数: MYSQL_HOST = 'localhost' MYSQL_DBNAME = 'bole' MYSQL_USER = 'root' MYSQL_PASSWD = '123456'

七 下载图片

素材中国图片网站:http://sc.chinaz.com/首页,找到 “图标” 分类;进入 图标 分类后,获取列表页的分类名称,列表页的详情页地址;请求详情页,将某一个分类的所有图标下载到本地,将每一个分类名称作为文件夹,内部保存该分类下的所有图片;自定义图片路径,自定义图片名称;

在pipelines.py中:

from scrapy.pipelines.images import ImagesPipeline from scrapy.http import Request # class TubiaoPipeline(object): # def process_item(self, item, spider): # return item class TubiaoSrcPipeline(ImagesPipeline): def get_media_requests(self, item, info):         # src 是图片的网址         # 只是保存图片的网址,不下载的话, tubiao['src'] = src               # 下载图片 图片的网址 在存入items中时, 必须是列表如: tubiao['src'] = [src]         image_src = item['src'][0] yield Request(image_src, meta={'item': item}) def file_path(self, request, response=None, info=None): # 自定义图片下载路径 item = request.meta['item']        # 分类的名字         title = item['title']         # 图片的名字自定义 这是没有加密的         # scrapy 自带的下载图片 图片的名字是加密过的         name = item['src'][0].split('/')[-1] path = title + '/' + name return path def item_completed(self, results, item, info): print(results) return item

配置settings.py文件:

# 配置图片的保存目录 IMAGES_STORE = 'imgs' # 在ImagesPipeline进行下载图片是,配置图片url对应的Item字段 IMAGES_URLS_FIELD = 'src' ITEM_PIPELINES = {       # 启用scrapy自带的图片下载ImagesPipeline, 'scrapy.pipelines.images.ImagesPipeline': None,          # 如果采用自定义的TubiaoSrcPipeline,需要将自带的ImagesPipeline设置为None。否则scrapy自带的也会下载 'Tubiao.pipelines.TubiaoSrcPipeline': 300, }

八 下载文件

与下载图片类似

在pipelines.py中:

class QsFilesPipeline(FilesPipeline): def get_media_requests(self, item, info): file_src = item['txt_url'][0] yield Request(file_src, meta={'item': item}) def file_path(self, request, response=None, info=None): item = request.meta['item']         # 分类文件名         title = item['file_img']         # 文件名         name = item['txt_url'][0].split('/')[-1]         # 分类下载         path = title + '/' + name return path def item_completed(self, results, item, info): print(results) return item

配置settings.py文件:

# 配置小说文件的下载路径和对应的下载字段 FILES_STORE = 'files' FILES_URLS_FIELD = 'txt_url' ITEM_PIPELINES = { # 'scrapy.pipelines.files.FilesPipeline': None, # 'Qishu.pipelines.QsFilesPipeline': 300, }

转载请注明原文地址: https://www.6miu.com/read-2620174.html

最新回复(0)