21、 Python快速开发分布式搜索引擎Scrapy精讲—爬虫数据保存
注意:数据保存的操作都是在pipelines.py文件里操作的
将数据保存为json文件
spider是一个信号检测
# -*- coding: utf-8 -*-
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html
from scrapy.pipelines.images import ImagesPipeline #导入图片下载器模块
import codecs
import json
class AdcPipeline(object): #定义数据处理类,必须继承object
def __init__(self):
self.file = codecs.open('shuju.json', 'w', encoding='utf-8') #初始化时打开json文件
def process_item(self, item, spider): #process_item(item)为数据处理函数,接收一个item,item里就是爬虫最后yield item 来的数据对象
# print('文章标题是:' + item['title'][0])
# print('文章缩略图url是:' + item['img'][0])
# print('文章缩略图保存路径是:' + item['img_tplj']) #接收图片下载器填充的,图片下载后的路径
#将数据保存为json文件
lines = json.dumps(dict(item), ensure_ascii=False) + '\n' #将数据对象转换成json格式
self.file.write(lines) #将json格式数据写入文件
return item
def spider_closed(self,spider): #创建一个方法继承spider,spider是一个信号,当前数据操作完成后触发这个方法
self.file.close() #关闭打开文件
class imgPipeline(ImagesPipeline): #自定义一个图片下载内,继承crapy内置的ImagesPipeline图片下载器类
def item_completed(self, results, item, info): #使用ImagesPipeline类里的item_completed()方法获取到图片下载后的保存路径
for ok, value in results:
img_lj = value['path'] #接收图片保存路径
# print(ok)
item['img_tplj'] = img_lj #将图片保存路径填充到items.py里的字段里
return item #将item给items.py 文件的容器函数
#注意:自定义图片下载器设置好后,需要在
将数据保存到数据库
我们使用一个ORM框架sqlalchemy模块,保存数据
数据库操作文件
#!/usr/bin/env python
# -*- coding:utf-8 -*-
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column
from sqlalchemy import Integer, String, TIMESTAMP
from sqlalchemy import ForeignKey, UniqueConstraint, Index
from sqlalchemy.orm import sessionmaker, relationship
from sqlalchemy import create_engine
#配置数据库引擎信息
ENGINE = create_engine("mysql+pymysql://root:279819@127.0.0.1:3306/cshi?charset=utf8", max_overflow=10, echo=True)
Base = declarative_base() #创建一个SQLORM基类
class SendMsg(Base): #设计表
__tablename__ = 'sendmsg'
id = Column(Integer, primary_key=True, autoincrement=True)
title = Column(String(300))
img_tplj = Column(String(300))
def init_db():
Base.metadata.create_all(ENGINE) #向数据库创建指定表
def drop_db():
Base.metadata.drop_all(ENGINE) #向数据库删除指定表
def session():
cls = sessionmaker(bind=ENGINE) #创建sessionmaker类,操作表
return cls()
# drop_db() #删除表
# init_db() #创建表
pipelines.py文件
# -*- coding: utf-8 -*-
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html
from scrapy.pipelines.images import ImagesPipeline #导入图片下载器模块
from adc import shujuku as ORM #导入数据库文件
class AdcPipeline(object): #定义数据处理类,必须继承object
def __init__(self):
ORM.init_db() #创建数据库表
def process_item(self, item, spider): #process_item(item)为数据处理函数,接收一个item,item里就是爬虫最后yield item 来的数据对象
print('文章标题是:' + item['title'][0])
print('文章缩略图url是:' + item['img'][0])
print('文章缩略图保存路径是:' + item['img_tplj']) #接收图片下载器填充的,图片下载后的路径
mysq = ORM.session()
shuju = ORM.SendMsg(title=item['title'][0], img_tplj=item['img_tplj'])
mysq.add(shuju)
mysq.commit()
return item
class imgPipeline(ImagesPipeline): #自定义一个图片下载内,继承crapy内置的ImagesPipeline图片下载器类
def item_completed(self, results, item, info): #使用ImagesPipeline类里的item_completed()方法获取到图片下载后的保存路径
for ok, value in results:
img_lj = value['path'] #接收图片保存路径
# print(ok)
item['img_tplj'] = img_lj #将图片保存路径填充到items.py里的字段里
return item #将item给items.py 文件的容器函数
#注意:自定义图片下载器设置好后,需要在
【转载自:http://www.lqkweb.com】

低调大师中文资讯倾力打造互联网数据资讯、行业资源、电子商务、移动互联网、网络营销平台。
持续更新报道IT业界、互联网、市场资讯、驱动更新,是最及时权威的产业资讯及硬件资讯报道平台。
转载内容版权归作者及来源网站所有,本站原创内容转载请注明来源。
-
上一篇
Python3入门(三)基本数据类型
Python 中的变量不需要声明。每个变量在使用前都必须赋值,变量赋值以后该变量才会被创建。在 Python 中,变量就是变量,它没有类型,我们所说的"类型"是变量所指的内存中对象的类型。等号(=)用来给变量赋值。等号(=)运算符左边是一个变量名,等号(=)运算符右边是存储在变量中的值。例如: count = 10 name = "python" price = 12.5 也支持同时为多个变量赋值。例如 a = b = c = 1 e, f, g = 1, 2, 3 如果想删除一个变量,可以使用del,删除后将不能在进行调用,例如 a = b = c = 1 del a, b Python的数据类型 Number(数字) String(字符串) List(列表) Tuple(元组) Set(集合) dictionary(字典) 不可变数据(3 个):Num
-
下一篇
javascript前端开发:阿里巴巴超难面试题让你理解call的用法
关于javascript中的call方法,网上总很难找到全面而通俗的解释,就我个人的理解来说,call有两个作用: 1、继承 2、修改函数运行时的this指针。 下面这段代码来自阿里的前端面试题库 function fn(a,b){ console.log(this); console.log(a); console.log(a+b); } fn.call(1); fn.call.call(fn); fn.call.call.call(fn,1,2); fn.call.call.call.call(fn,1,2,3); 答案: fn.call(1); // 1,undefined,NaN fn.call.call(fn); // fn,undefined,NaN fn.call.call.call(fn,1,2); // 1,2,NaN fn.call.call.call.call(fn,1,2,3); // 1,2,5 题解: fn.call(1);call的第一个参数改变call前面函数里的关键字this所以输出1;后面没有参数所以a,b为undefined,相加结果为NaN; f...
相关文章
文章评论
共有0条评论来说两句吧...
文章二维码
点击排行
推荐阅读
最新文章
- SpringBoot2整合Redis,开启缓存,提高访问速度
- 设置Eclipse缩进为4个空格,增强代码规范
- Windows10,CentOS7,CentOS8安装MongoDB4.0.16
- SpringBoot2全家桶,快速入门学习开发网站教程
- CentOS7编译安装Cmake3.16.3,解决mysql等软件编译问题
- Docker快速安装Oracle11G,搭建oracle11g学习环境
- SpringBoot2整合MyBatis,连接MySql数据库做增删改查操作
- Springboot2将连接池hikari替换为druid,体验最强大的数据库连接池
- SpringBoot2配置默认Tomcat设置,开启更多高级功能
- SpringBoot2更换Tomcat为Jetty,小型站点的福音