抓取到的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. How to determine what causes a particular wait type

      By: Paul Randal Posted on: March 18, 2014 6:55 pm   [Edit 2016: Check out my new resource – a comp ...

  2. Vue 单页应用:记事本

    若文章中存在内容无法加载的情况,请移步作者其他博客. 简书 CSDN 最近在看 Vue 的时候,别人给我安利了一个国外的小案例,通过 Vue 和 Vuex 来实现一个记事本. 仔细剖析下,发现“麻雀虽 ...

  3. 简单抓取安居客房产数据,并保存到Oracle数据库

    思路和上一篇差不多,先获取网站html文件,使用BeautifulSoup进行解析,将对应属性取出,逐一处理,最后把整理出的记录保存到oracle中,持久化储存. '''Created on 2017 ...

  4. HTTPS.SYS怎样使用HTTPS

    HTTPS.SYS怎样使用HTTPS 参考了MORMOT的官方文档:http://blog.synopse.info/post/2013/09/04/HTTPS-communication-in-mO ...

  5. inner join, left join ,right join 结果

    假设有两个表结构如下: 表table1 表 table 2 内连接: --内连接 select * from table1 inner join table2 on table1.ID = table ...

  6. Android API level 版本对应关系

    详情地址:http://developer.android.com/guide/topics/manifest/uses-sdk-element.html Platform Version API L ...

  7. Chrome插件——一键保存网页为PDF1.0发布

    最新版本:V1.1 下载地址:http://download.csdn.net/detail/bdstjk/5722317 发布时间:2013-7-8 版本号:1.1.7.80 更新内容: 1.增加检 ...

  8. PHP文件包含漏洞总结

    0x00 前言 PHP文件包含漏洞的产生原因是在通过PHP的函数引入文件时,由于传入的文件名没有经过合理的校验,从而操作了预想之外的文件,就可能导致意外的文件泄露甚至恶意的代码注入. 最常见的就属于本 ...

  9. 解决Spark集群无法停止

    执行stop-all.sh时,出现报错:no org.apache.spark.deploy.master.Master to stop,no org.apache.spark.deploy.work ...

  10. Linux命令未找到(command not found),误删Linux path原始路径

    1.执行:/bin/vim /etc/profile (打开并编辑profile将Path修改正确,然后保存退出) 2.执行:export PATH=/usr/bin:/usr/sbin:/bin:/ ...