抓取到的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 将抓取到的数据存入数据库与验证数据有效性的更多相关文章

  1. Scrapy爬虫入门系列2 示例教程

    本来想爬下http://www.alexa.com/topsites/countries/CN 总排名的,但是收费了 只爬了50条数据: response.xpath('//div[@class=&q ...

  2. Scrapy爬虫入门系列4抓取豆瓣Top250电影数据

    豆瓣有些电影页面需要登录才能查看. 目录 [隐藏]  1 创建工程 2 定义Item 3 编写爬虫(Spider) 4 存储数据 5 配置文件 6 艺搜参考 创建工程 scrapy startproj ...

  3. Scrapy爬虫入门系列1 安装

    安装python2.7 参见CentOS升级python 2.6到2.7 安装pip 参见CentOS安装python setuptools and pip‎ 依赖 https://docs.scra ...

  4. python网络爬虫抓取动态网页并将数据存入数据库MySQL

    简述以下的代码是使用python实现的网络爬虫,抓取动态网页 http://hb.qq.com/baoliao/ .此网页中的最新.精华下面的内容是由JavaScript动态生成的.审查网页元素与网页 ...

  5. scrapy爬虫学习系列四:portia的学习入门

    系列文章列表: scrapy爬虫学习系列一:scrapy爬虫环境的准备:      http://www.cnblogs.com/zhaojiedi1992/p/zhaojiedi_python_00 ...

  6. scrapy爬虫学习系列五:图片的抓取和下载

    系列文章列表: scrapy爬虫学习系列一:scrapy爬虫环境的准备:      http://www.cnblogs.com/zhaojiedi1992/p/zhaojiedi_python_00 ...

  7. scrapy爬虫学习系列二:scrapy简单爬虫样例学习

    系列文章列表: scrapy爬虫学习系列一:scrapy爬虫环境的准备:      http://www.cnblogs.com/zhaojiedi1992/p/zhaojiedi_python_00 ...

  8. scrapy爬虫学习系列一:scrapy爬虫环境的准备

    系列文章列表: scrapy爬虫学习系列一:scrapy爬虫环境的准备:      http://www.cnblogs.com/zhaojiedi1992/p/zhaojiedi_python_00 ...

  9. scrapy爬虫学习系列三:scrapy部署到scrapyhub上

    系列文章列表: scrapy爬虫学习系列一:scrapy爬虫环境的准备:      http://www.cnblogs.com/zhaojiedi1992/p/zhaojiedi_python_00 ...

随机推荐

  1. [测试技术分享]DNS域传送漏洞测试

    DNS域传送漏洞测试 1.简介: DNS(Domain Name System)也叫域名管理系统,它它建立在一个分布式数据库基础之上,在这个数据库里,保存了IP地址和域名的相互映射关系.正因为DNS的 ...

  2. Matlab设置形状大小

    x=0:10; y=2*x; plot(x,y,'-*','linewidth',0.5,'markersize',6)%%默认线宽为0.5,点大小为6 说明:调整线宽也可改变点的形状,这实际上是通过 ...

  3. 直接拿来用!最火的iOS开源项目(二)

    每一次的改变总意味着新的开始.”这句话用在iOS上可谓是再合适不过的了.GitHub上的iOS开源项目数不胜数,iOS每一次的改变,总会引发iOS开源项目的演变,从iOS 1.x到如今的iOS 7,有 ...

  4. Java开发中的23种设计模式详解 【转】

    创建型模式,共五种:工厂方法模式.抽象工厂模式.单例模式.建造者模式.原型模式. 行为型模式,共十一种:策略模式.模板方法模式.观察者模式.迭代子模式.责任链模式.命令模式.备忘录模式.状态模式.访问 ...

  5. ISP图像调试工程师——3D和2D降噪(熟悉图像预处理和后处理技术)

    2D降噪:只在2维空间域上进行降噪处理.基本方法:对一个像素将其与周围像素平均,平均后噪声降低,但缺点是会造成画面模糊,特别是物体边缘部分.因此对这种算法的改进主要是进行边缘检测,边缘部分的像素不用来 ...

  6. JavaScript中的bind方法及其常见应用

    一.bind()方法的实现 在JavaScript中,方法往往涉及到上下文,也就是this,因此往往不能直接引用.就拿最常见的console.log("info…")来说,避免书写 ...

  7. NDK官方开发指南翻译之 NDK_GDB

    这几天看JNI,没有基础,那真是难受--把看到的相关资料记录一下,也分享给刚開始学习的人. 'ndk-gdb' Overview 重要:假设你要调试线程相关的程序.请阅读以下的'Thread Supp ...

  8. [Functional Programming] Combine Multiple State ADT Instances with the Same Input (converge(liftA2(constant)))

    When combining multiple State ADT instances that depend on the same input, using chain can become qu ...

  9. Eclipse重新导入Tomcat启动出错选择不了文件夹

    如果你已经把tomcat配置进了Eclipse,却因为某些原因delete了服务器,再想导入同版本的服务器就有可能会报Could not publish to the server.错误,并且添加服务 ...

  10. Jquery DataTables 自定义布局sdom

    Jquery DataTables 自定义布局sdom JQuery Datatable sDom 配置 官网给的描述是: This initialisation variable allows yo ...