Scrapy爬虫入门系列3 将抓取到的数据存入数据库与验证数据有效性
抓取到的item 会被发送到Item Pipeline进行处理
Item Pipeline常用于
- cleansing HTML data
- validating scraped data (checking that the items contain certain fields)
- checking for duplicates (and dropping them)
- storing the scraped item in a database
目录[隐藏] |
写一个自己的item pipeline
就是写一个Python类,并且实现process_item(item, spider)方法
must either return a Item (or any descendant子孙 class) object or raise a DropItem exception.
Price validation and dropping items with no prices
adjusts the price attribute for those items that do not include VAT (price_excludes_vat attribute), and drops those items which don’t contain a price:
如果没有price则丢掉,如果没有price_excludes_vat,调整价格值。
from scrapy.exceptions import DropItem class PricePipeline(object): vat_factor =1.15 def process_item(self, item, spider): if item['price']: if item['price_excludes_vat']: item['price']= item['price'] * self.vat_factor
return item else: raise DropItem("Missing price in %s" % item)
写到JSON文件中
import json class JsonWriterPipeline(object): def__init__(self): self.file=open('items.jl','wb') def process_item(self, item, spider): line = json.dumps(dict(item)) + "\n"
self.file.write(line)
return item
Duplicates filter
A filter that looks for duplicate items, and drops those items that were already processed. Let say that our items have an unique id, but our spider returns multiples items with the same id:
from scrapy.exceptionsimport DropItem class DuplicatesPipeline(object): def__init__(self): self.ids_seen=set() def process_item(self, item, spider): if item['id']in self.ids_seen: raise DropItem("Duplicate item found: %s" % item)
else: self.ids_seen.add(item['id'])
return item
Activating激活 an Item Pipeline component
在settings.py中加入如下代码:
ITEM_PIPELINES ={'myproject.pipelines.PricePipeline': 300,'myproject.pipelines.JsonWriterPipeline': 800,}
我们在Scrapy爬虫入门系列2:示例教程的基础上,支持json输出
- 1,先写好pipeline
import json class TutorialPipeline(object): def__init__(self): self.file=open('output.json','wb') def process_item(self, item, spider): line = json.dumps(dict(item)) + "\n"
self.file.write(line)
return item
- 2,然后在settings.py中加入
ITEM_PIPELINES={'tutorial.pipelines.TutorialPipeline':400,}
最后运行scrapy crawl dmoz会生成output.json。
存入数据库
打开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 # -*- coding: utf-8 -*-
from scrapy import log from twisted.enterprise import adbapi from scrapy.httpimport Request from scrapy.selectorimport HtmlXPathSelector import urllib import MySQLdb import MySQLdb.cursors class TutorialPipeline(object): def__init__(self): self.dbpool= adbapi.ConnectionPool('MySQLdb',db ='scrapy',user='root',passwd ='pwd', cursorclass = MySQLdb.cursors.DictCursor, charset ='utf8', use_unicode =False)
def process_item(self, item, spider): query =self.dbpool.runInteraction(self._conditional_insert, item) query.addErrback(self.handle_error)
return item def _conditional_insert(self,tx,item): tx.execute("select * from item where title = %s",(item['title'])) result=tx.fetchone()
# log.msg(result,level=log.DEBUG)#print result
if result: log.msg("Item already stored in db:%s" % item,level=log.DEBUG)
else: tx.execute("insert into item (title) values (%s)",(item['title']))
def handle_error(self, e): log.err(e)
请注意python的缩进,不然会报错。
然后在settings.py里加上:
ITEM_PIPELINES={'tutorial.pipelines.TutorialPipeline':400,}
运行scrapy crawl dmoz,会发现数据成功插入到数据库中:

如果报错:
No module named MySQLdb
解决:
yum install MySQL-python pip install mysql-python
源码下载:艺搜下载
[编辑]艺搜参考
http://doc.scrapy.org/en/latest/topics/item-pipeline.html
http://stackoverflow.com/questions/10845839/writing-items-to-a-mysql-database-in-scrapy
http://www.cnblogs.com/lchd/p/3820968.html
Scrapy爬虫入门系列3 将抓取到的数据存入数据库与验证数据有效性的更多相关文章
- Scrapy爬虫入门系列2 示例教程
本来想爬下http://www.alexa.com/topsites/countries/CN 总排名的,但是收费了 只爬了50条数据: response.xpath('//div[@class=&q ...
- Scrapy爬虫入门系列4抓取豆瓣Top250电影数据
豆瓣有些电影页面需要登录才能查看. 目录 [隐藏] 1 创建工程 2 定义Item 3 编写爬虫(Spider) 4 存储数据 5 配置文件 6 艺搜参考 创建工程 scrapy startproj ...
- Scrapy爬虫入门系列1 安装
安装python2.7 参见CentOS升级python 2.6到2.7 安装pip 参见CentOS安装python setuptools and pip 依赖 https://docs.scra ...
- python网络爬虫抓取动态网页并将数据存入数据库MySQL
简述以下的代码是使用python实现的网络爬虫,抓取动态网页 http://hb.qq.com/baoliao/ .此网页中的最新.精华下面的内容是由JavaScript动态生成的.审查网页元素与网页 ...
- scrapy爬虫学习系列四:portia的学习入门
系列文章列表: scrapy爬虫学习系列一:scrapy爬虫环境的准备: http://www.cnblogs.com/zhaojiedi1992/p/zhaojiedi_python_00 ...
- scrapy爬虫学习系列五:图片的抓取和下载
系列文章列表: scrapy爬虫学习系列一:scrapy爬虫环境的准备: http://www.cnblogs.com/zhaojiedi1992/p/zhaojiedi_python_00 ...
- scrapy爬虫学习系列二:scrapy简单爬虫样例学习
系列文章列表: scrapy爬虫学习系列一:scrapy爬虫环境的准备: http://www.cnblogs.com/zhaojiedi1992/p/zhaojiedi_python_00 ...
- scrapy爬虫学习系列一:scrapy爬虫环境的准备
系列文章列表: scrapy爬虫学习系列一:scrapy爬虫环境的准备: http://www.cnblogs.com/zhaojiedi1992/p/zhaojiedi_python_00 ...
- scrapy爬虫学习系列三:scrapy部署到scrapyhub上
系列文章列表: scrapy爬虫学习系列一:scrapy爬虫环境的准备: http://www.cnblogs.com/zhaojiedi1992/p/zhaojiedi_python_00 ...
随机推荐
- 记录一次Elasticsearch线上部署后出现:org.elasticsearch.client.transport.NoNodeAvailableException: None of the configured nodes are available: []的问题解决
说明:ES部署了3个节点,而一般情况只要这三个节点的IP其中一个都可以连接,Web端口使用的是9500,Client连接使用的是9600,调用程序使用了ES原生Client进行连接. 解决方法: 1. ...
- dwz中弹出的窗口页面如何获取前页面(点击按钮的页面)的元素???
在页面A.jsp中点击一个按钮,使用$.pdialog.open()方法弹出b.jsp页面(对话框窗口),我要在b.jsp中选中值然后关闭窗口(b.jsp)返回值给A.jsp~ =========== ...
- 开源的库RestSharp轻松消费Restful Service
现在互联网上的服务接口都是Restful的,SOAP的Service已经不是主流..NET/Mono下如何消费Restful Service呢,再也没有了方便的Visual Studio的方便生产代理 ...
- Objective-C:运行时runtime
1.是否可以把比较耗时的操作放在通知中心中? 通知在哪一个线程发的,那么对通知事件的处理就在同一个线程中进行; 如果在异步线程发的通知,那么可以执行比较耗时的操作: 如果在主线程发的通知,那么就不 ...
- IE漏洞调试之CVE-2013-3893
前言 Windows平台的漏洞挖掘和安全研究中,IE始终是绕不开的话题.IE漏洞就跟adobe系列一样经典,是学习exploit.shellcode的绝佳途径. 在IE漏洞中,UAF即Use-Afte ...
- IOS Vsync
vsync count Don't Sync Application.targetFrameRate 设置FPS上限 Every Second VBlank 30 Every VBlank 60 An ...
- webpack配置:图片处理、css分离和路径问题
一.CSS中的图片处理: 1.首先在网上随便找一张图片,在src下新建images文件夹,将图片放在文件夹内 2.在index.html中写入代码:<div id="pic" ...
- Java源码阅读LinkedHashMap
1类签名与注释 public class LinkedHashMap<K,V> extends HashMap<K,V> implements Map<K,V> 哈 ...
- kubelet分析
kubelet是k8s中节点上运行的管理工具,它负责接受api-server发送的调度请求,在Node上创建管理pod,并且向api-server同步节点的状态.这篇文章主要讲讲kubelet组件如何 ...
- Spark(二) -- Spark简单介绍
spark是什么? spark开源的类Hadoop MapReduce的通用的并行计算框架 spark基于map reduce算法实现的分布式计算 拥有Hadoop MapReduce所具有的优点 但 ...