Python的Scrapy爬虫框架简单学习笔记


Posted in Python onJanuary 20, 2016

 一、简单配置,获取单个网页上的内容。
(1)创建scrapy项目

scrapy startproject getblog

(2)编辑 items.py

# -*- coding: utf-8 -*-
 
# Define here the models for your scraped items
#
# See documentation in:
# http://doc.scrapy.org/en/latest/topics/items.html
 
from scrapy.item import Item, Field
 
class BlogItem(Item):
  title = Field()
  desc = Field()

    (3)在 spiders 文件夹下,创建 blog_spider.py

需要熟悉下xpath选择,感觉跟JQuery选择器差不多,但是不如JQuery选择器用着舒服( w3school教程: http://www.w3school.com.cn/xpath/  )。

# coding=utf-8
 
from scrapy.spider import Spider
from getblog.items import BlogItem
from scrapy.selector import Selector
 
 
class BlogSpider(Spider):
  # 标识名称
  name = 'blog'
  # 起始地址
  start_urls = ['http://www.cnblogs.com/']
 
  def parse(self, response):
    sel = Selector(response) # Xptah 选择器
    # 选择所有含有class属性,值为‘post_item'的div 标签内容
    # 下面的 第2个div 的 所有内容
    sites = sel.xpath('//div[@class="post_item"]/div[2]')
    items = []
    for site in sites:
      item = BlogItem()
      # 选取h3标签下,a标签下,的文字内容 ‘text()'
      item['title'] = site.xpath('h3/a/text()').extract()
      # 同上,p标签下的 文字内容 ‘text()'
      item['desc'] = site.xpath('p[@class="post_item_summary"]/text()').extract()
      items.append(item)
    return items

(4)运行,

scrapy crawl blog # 即可

(5)输出文件。

        在 settings.py 中进行输出配置。

# 输出文件位置
FEED_URI = 'blog.xml'
# 输出文件格式 可以为 json,xml,csv
FEED_FORMAT = 'xml'

    输出位置为项目根文件夹下。

二、基本的 -- scrapy.spider.Spider

    (1)使用交互shell

dizzy@dizzy-pc:~$ scrapy shell "http://www.baidu.com/"
2014-08-21 04:09:11+0800 [scrapy] INFO: Scrapy 0.24.4 started (bot: scrapybot)
2014-08-21 04:09:11+0800 [scrapy] INFO: Optional features available: ssl, http11, django
2014-08-21 04:09:11+0800 [scrapy] INFO: Overridden settings: {'LOGSTATS_INTERVAL': 0}
2014-08-21 04:09:11+0800 [scrapy] INFO: Enabled extensions: TelnetConsole, CloseSpider, WebService, CoreStats, SpiderState
2014-08-21 04:09:11+0800 [scrapy] INFO: Enabled downloader middlewares: HttpAuthMiddleware, DownloadTimeoutMiddleware, UserAgentMiddleware, RetryMiddleware, DefaultHeadersMiddleware, MetaRefreshMiddleware, HttpCompressionMiddleware, RedirectMiddleware, CookiesMiddleware, ChunkedTransferMiddleware, DownloaderStats
2014-08-21 04:09:11+0800 [scrapy] INFO: Enabled spider middlewares: HttpErrorMiddleware, OffsiteMiddleware, RefererMiddleware, UrlLengthMiddleware, DepthMiddleware
2014-08-21 04:09:11+0800 [scrapy] INFO: Enabled item pipelines: 
2014-08-21 04:09:11+0800 [scrapy] DEBUG: Telnet console listening on 127.0.0.1:6024
2014-08-21 04:09:11+0800 [scrapy] DEBUG: Web service listening on 127.0.0.1:6081
2014-08-21 04:09:11+0800 [default] INFO: Spider opened
2014-08-21 04:09:12+0800 [default] DEBUG: Crawled (200) <GET http://www.baidu.com/> (referer: None)
[s] Available Scrapy objects:
[s]  crawler  <scrapy.crawler.Crawler object at 0xa483cec>
[s]  item    {}
[s]  request  <GET http://www.baidu.com/>
[s]  response  <200 http://www.baidu.com/>
[s]  settings  <scrapy.settings.Settings object at 0xa0de78c>
[s]  spider   <Spider 'default' at 0xa78086c>
[s] Useful shortcuts:
[s]  shelp()      Shell help (print this help)
[s]  fetch(req_or_url) Fetch request (or URL) and update local objects
[s]  view(response)  View response in a browser
 
>>> 
  # response.body 返回的所有内容
  # response.xpath('//ul/li') 可以测试所有的xpath内容
    More important, if you type response.selector you will access a selector object you can use to
query the response, and convenient shortcuts like response.xpath() and response.css() mapping to
response.selector.xpath() and response.selector.css()

        也就是可以很方便的,以交互的形式来查看xpath选择是否正确。之前是用FireFox的F12来选择的,但是并不能保证每次都能正确的选择出内容。

        也可使用:

scrapy shell 'http://scrapy.org' --nolog
# 参数 --nolog 没有日志

    (2)示例

from scrapy import Spider
from scrapy_test.items import DmozItem
 
 
class DmozSpider(Spider):
  name = 'dmoz'
  allowed_domains = ['dmoz.org']
  start_urls = ['http://www.dmoz.org/Computers/Programming/Languages/Python/Books/',
         'http://www.dmoz.org/Computers/Programming/Languages/Python/Resources/,'
         '']
 
  def parse(self, response):
    for sel in response.xpath('//ul/li'):
      item = DmozItem()
      item['title'] = sel.xpath('a/text()').extract()
      item['link'] = sel.xpath('a/@href').extract()
      item['desc'] = sel.xpath('text()').extract()
      yield item

    (3)保存文件

        可以使用,保存文件。格式可以 json,xml,csv

scrapy crawl -o 'a.json' -t 'json'

    (4)使用模板创建spider

scrapy genspider baidu baidu.com
 
# -*- coding: utf-8 -*-
import scrapy
 
 
class BaiduSpider(scrapy.Spider):
  name = "baidu"
  allowed_domains = ["baidu.com"]
  start_urls = (
    'http://www.baidu.com/',
  )
 
  def parse(self, response):
    pass

    这段先这样吧,记得之前5个的,现在只能想起4个来了. :-(

    千万记得随手点下保存按钮。否则很是影响心情的(⊙o⊙)!

三、高级 -- scrapy.contrib.spiders.CrawlSpider

例子

#coding=utf-8
from scrapy.contrib.spiders import CrawlSpider, Rule
from scrapy.contrib.linkextractors import LinkExtractor
import scrapy
 
 
class TestSpider(CrawlSpider):
  name = 'test'
  allowed_domains = ['example.com']
  start_urls = ['http://www.example.com/']
  rules = (
    # 元组
    Rule(LinkExtractor(allow=('category\.php', ), deny=('subsection\.php', ))),
    Rule(LinkExtractor(allow=('item\.php', )), callback='pars_item'),
  )
 
  def parse_item(self, response):
    self.log('item page : %s' % response.url)
    item = scrapy.Item()
    item['id'] = response.xpath('//td[@id="item_id"]/text()').re('ID:(\d+)')
    item['name'] = response.xpath('//td[@id="item_name"]/text()').extract()
    item['description'] = response.xpath('//td[@id="item_description"]/text()').extract()
    return item

其他的还有 XMLFeedSpider

  • class scrapy.contrib.spiders.XMLFeedSpider
  • class scrapy.contrib.spiders.CSVFeedSpider
  • class scrapy.contrib.spiders.SitemapSpider

四、选择器

>>> from scrapy.selector import Selector
  >>> from scrapy.http import HtmlResponse

    可以灵活的使用 .css() 和 .xpath() 来快速的选取目标数据

关于选择器,需要好好研究一下。xpath() 和 css() ,还要继续熟悉 正则.

    当通过class来进行选择的时候,尽量使用 css() 来选择,然后再用 xpath() 来选择元素的熟悉

五、Item Pipeline

Typical use for item pipelines are:
    • cleansing HTML data # 清除HTML数据
    • validating scraped data (checking that the items contain certain fields) # 验证数据
    • checking for duplicates (and dropping them) # 检查重复
    • storing the scraped item in a database # 存入数据库
    (1)验证数据

from scrapy.exceptions import DropItem
 
class PricePipeline(object):
  vat_factor = 1.5
  def process_item(self, item, spider):
    if item['price']:
      if item['price_excludes_vat']:
        item['price'] *= self.vat_factor
    else:
      raise DropItem('Missing price in %s' % item)

    (2)写Json文件

import json
 
class JsonWriterPipeline(object):
  def __init__(self):
    self.file = open('json.jl', 'wb')
  def process_item(self, item, spider):
    line = json.dumps(dict(item)) + '\n'
    self.file.write(line)
    return item

    (3)检查重复

from scrapy.exceptions import DropItem
 
class Duplicates(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

    至于将数据写入数据库,应该也很简单。在 process_item 函数中,将 item 存入进去即可了。

Python 相关文章推荐
python结合opencv实现人脸检测与跟踪
Jun 08 Python
python比较两个列表大小的方法
Jul 11 Python
python 连接sqlite及简单操作
Jun 30 Python
Python图像处理之识别图像中的文字(实例讲解)
May 10 Python
pandas DataFrame实现几列数据合并成为新的一列方法
Jun 08 Python
Python使用pymongo模块操作MongoDB的方法示例
Jul 20 Python
详解python 3.6 安装json 模块(simplejson)
Apr 02 Python
关于python3中setup.py小概念解析
Aug 22 Python
python3 webp转gif格式的实现示例
Dec 10 Python
django为Form生成的label标签添加class方式
May 20 Python
openCV提取图像中的矩形区域
Jul 21 Python
numpy数据类型dtype转换实现
Apr 24 Python
使用Python编写爬虫的基本模块及框架使用指南
Jan 20 #Python
Python中urllib+urllib2+cookielib模块编写爬虫实战
Jan 20 #Python
深入剖析Python的爬虫框架Scrapy的结构与运作流程
Jan 20 #Python
实践Python的爬虫框架Scrapy来抓取豆瓣电影TOP250
Jan 20 #Python
Python的爬虫包Beautiful Soup中用正则表达式来搜索
Jan 20 #Python
Python使用Beautiful Soup包编写爬虫时的一些关键点
Jan 20 #Python
Python制作爬虫抓取美女图
Jan 20 #Python
You might like
深入PHP curl参数的详解
2013/06/17 PHP
PHP常用的缓存技术汇总
2014/05/05 PHP
jQuery 使用手册(三)
2009/09/23 Javascript
28个JS验证函数收集
2010/03/02 Javascript
jQuery AJAX实现调用页面后台方法和web服务定义的方法分享
2012/03/01 Javascript
js实现通用的微信分享组件示例
2014/03/10 Javascript
JavaScript制作的可折叠弹出式菜单示例
2014/04/04 Javascript
javascript删除数组重复元素的方法汇总
2015/06/24 Javascript
超级给力的JavaScript的React框架入门教程
2015/07/02 Javascript
理解 JavaScript Scoping &amp; Hoisting(二)
2015/11/18 Javascript
一些实用性较高的js方法
2016/04/19 Javascript
AngularJS基础 ng-csp 指令详解
2016/08/01 Javascript
JS当前页面登录注册框,固定DIV,底层阴影的实例代码
2016/09/29 Javascript
详解webpack和webpack-simple中如何引入css文件
2017/06/28 Javascript
vue-cli 自定义指令directive 添加验证滑块示例
2017/10/19 Javascript
jQuery zTree 异步加载添加子节点重复问题
2017/11/29 jQuery
vue.js中引入vuex储存接口数据及调用的详细流程
2017/12/14 Javascript
JS实现简易换图时钟功能分析
2018/01/04 Javascript
JavaScript基础心法 深浅拷贝(浅拷贝和深拷贝)
2018/03/05 Javascript
vue使用Element组件时v-for循环里的表单项验证方法
2018/06/28 Javascript
更改BootStrap popover的默认样式及popover简单用法
2018/09/13 Javascript
使用Vue中 v-for循环列表控制按钮隐藏显示功能
2019/04/23 Javascript
[01:09]2014DOTA2国际邀请赛 TI4西雅图DOTA2 中国美女coser加油助威
2014/07/20 DOTA
python时间整形转标准格式的示例分享
2014/02/14 Python
Python多线程爬虫简单示例
2016/03/04 Python
python matplotlib 注释文本箭头简单代码示例
2018/01/08 Python
Python实现网页截图(PyQT5)过程解析
2019/08/12 Python
使用pickle存储数据dump 和 load实例讲解
2019/12/30 Python
浅谈Keras的Sequential与PyTorch的Sequential的区别
2020/06/17 Python
python爬虫线程池案例详解(梨视频短视频爬取)
2021/02/20 Python
Agoda香港:全球特价酒店预订
2017/05/07 全球购物
美国儿童珠宝在线零售商:Loveivy
2019/05/22 全球购物
工作自我推荐信范文
2015/03/25 职场文书
2015年勤工助学工作总结
2015/04/29 职场文书
准备去美国留学,那么大学申请文书应该怎么写?
2019/08/12 职场文书
python数字转对应中文的方法总结
2021/08/02 Python