Scrapy框架CrawlSpiders的介绍以及使用详解

在Scrapy基础——Spider中,我简要地说了一下Spider类。Spider基本上能做很多事情了,但是如果你想爬取知乎或者是简书全站的话,你可能需要一个更强大的武器。CrawlSpider基于Spider,但是可以说是为全站爬取而生。

CrawlSpiders是Spider的派生类,Spider类的设计原则是只爬取start_url列表中的网页,而CrawlSpider类定义了一些规则(rule)来提供跟进link的方便的机制,从爬取的网页中获取link并继续爬取的工作更适合。

一、我们先来分析一下CrawlSpiders源码

源码解析

class CrawlSpider(Spider):
  rules = ()
  def __init__(self, *a, **kw):
    super(CrawlSpider, self).__init__(*a, **kw)
    self._compile_rules()

  # 首先调用parse()来处理start_urls中返回的response对象
  # parse()则将这些response对象传递给了_parse_response()函数处理,并设置回调函数为parse_start_url()
  # 设置了跟进标志位True
  # parse将返回item和跟进了的Request对象
  def parse(self, response):
    return self._parse_response(response, self.parse_start_url, cb_kwargs={}, follow=True)

  # 处理start_url中返回的response,需要重写
  def parse_start_url(self, response):
    return []

  def process_results(self, response, results):
    return results

  # 从response中抽取符合任一用户定义'规则'的链接,并构造成Resquest对象返回
  def _requests_to_follow(self, response):
    if not isinstance(response, HtmlResponse):
      return
    seen = set()
    # 抽取之内的所有链接,只要通过任意一个'规则',即表示合法
    for n, rule in enumerate(self._rules):
      links = [l for l in rule.link_extractor.extract_links(response) if l not in seen]
      # 使用用户指定的process_links处理每个连接
      if links and rule.process_links:
        links = rule.process_links(links)
      # 将链接加入seen集合,为每个链接生成Request对象,并设置回调函数为_repsonse_downloaded()
      for link in links:
        seen.add(link)
        # 构造Request对象,并将Rule规则中定义的回调函数作为这个Request对象的回调函数
        r = Request(url=link.url, callback=self._response_downloaded)
        r.meta.update(rule=n, link_text=link.text)
        # 对每个Request调用process_request()函数。该函数默认为indentify,即不做任何处理,直接返回该Request.
        yield rule.process_request(r)

  # 处理通过rule提取出的连接,并返回item以及request
  def _response_downloaded(self, response):
    rule = self._rules[response.meta['rule']]
    return self._parse_response(response, rule.callback, rule.cb_kwargs, rule.follow)

  # 解析response对象,会用callback解析处理他,并返回request或Item对象
  def _parse_response(self, response, callback, cb_kwargs, follow=True):
    # 首先判断是否设置了回调函数。(该回调函数可能是rule中的解析函数,也可能是 parse_start_url函数)
    # 如果设置了回调函数(parse_start_url()),那么首先用parse_start_url()处理response对象,
    # 然后再交给process_results处理。返回cb_res的一个列表
    if callback:
      #如果是parse调用的,则会解析成Request对象
      #如果是rule callback,则会解析成Item
      cb_res = callback(response, **cb_kwargs) or ()
      cb_res = self.process_results(response, cb_res)
      for requests_or_item in iterate_spider_output(cb_res):
        yield requests_or_item

    # 如果需要跟进,那么使用定义的Rule规则提取并返回这些Request对象
    if follow and self._follow_links:
      #返回每个Request对象
      for request_or_item in self._requests_to_follow(response):
        yield request_or_item

  def _compile_rules(self):
    def get_method(method):
      if callable(method):
        return method
      elif isinstance(method, basestring):
        return getattr(self, method, None)

    self._rules = [copy.copy(r) for r in self.rules]
    for rule in self._rules:
      rule.callback = get_method(rule.callback)
      rule.process_links = get_method(rule.process_links)
      rule.process_request = get_method(rule.process_request)

  def set_crawler(self, crawler):
    super(CrawlSpider, self).set_crawler(crawler)
    self._follow_links = crawler.settings.getbool('CRAWLSPIDER_FOLLOW_LINKS', True)

二、 CrawlSpider爬虫文件字段的介绍

1、 CrawlSpider继承于Spider类,除了继承过来的属性外(name、allow_domains),还提供了新的属性和方法:class scrapy.linkextractors.LinkExtractorLink Extractors 的目的很简单: 提取链接。每个LinkExtractor有唯一的公共方法是 extract_links(),它接收一个 Response 对象,并返回一个 scrapy.link.Link 对象。

Link Extractors要实例化一次,并且 extract_links 方法会根据不同的 response 调用多次提取链接。

class scrapy.linkextractors.LinkExtractor(
  allow = (),
  deny = (),
  allow_domains = (),
  deny_domains = (),
  deny_extensions = None,
  restrict_xpaths = (),
  tags = ('a','area'),
  attrs = ('href'),
  canonicalize = True,
  unique = True,
  process_value = None
)

主要参数:

① allow:满足括号中“正则表达式”的值会被提取,如果为空,则全部匹配。
② deny:与这个正则表达式(或正则表达式列表)不匹配的URL一定不提取。
③ allow_domains:会被提取的链接的domains。
④ deny_domains:一定不会被提取链接的domains。
⑤ restrict_xpaths:使用xpath表达式,和allow共同作用过滤链接。

2、 在rules中包含一个或多个Rule对象,每个Rule对爬取网站的动作定义了特定操作。如果多个rule匹配了相同的链接,则根据规则在本集合中被定义的顺序,第一个会被使用。

class scrapy.spiders.Rule(
    link_extractor,
    callback = None,
    cb_kwargs = None,
    follow = None,
    process_links = None,
    process_request = None
)

① link_extractor:是一个Link Extractor对象,用于定义需要提取的链接。

② callback: 从link_extractor中每获取到链接时,参数所指定的值作为回调函数,该回调函数接受一个response作为其第一个参数。

注意:当编写爬虫规则时,避免使用parse作为回调函数。由于CrawlSpider使用parse方法来实现其逻辑,如果覆盖了 parse方法,crawl spider将会运行失败。

③ follow:是一个布尔(boolean)值,指定了根据该规则从response提取的链接是否需要跟进。 如果callback为None,follow 默认设置为True ,否则默认为False。

④ process_links:指定该spider中哪个的函数将会被调用,从link_extractor中获取到链接列表时将会调用该函数。该方法主要用来过滤。

⑤ process_request:指定该spider中哪个的函数将会被调用, 该规则提取到每个request时都会调用该函数。 (用来过滤request)

3、Scrapy提供了log功能,可以通过 logging 模块使用。可以修改配置文件settings.py,任意位置添加下面两行,效果会清爽很多。

LOG_FILE = "TencentSpider.log"
LOG_LEVEL = "INFO"

Scrapy提供5层logging级别:

① CRITICAL - 严重错误(critical)
② ERROR - 一般错误(regular errors)
③ WARNING - 警告信息(warning messages)
④ INFO - 一般信息(informational messages)
⑤ DEBUG - 调试信息(debugging messages)

通过在setting.py中进行以下设置可以被用来配置logging:

① LOG_ENABLED 默认: True,启用logging
② LOG_ENCODING 默认: 'utf-8',logging使用的编码
③ LOG_FILE 默认: None,在当前目录里创建logging输出文件的文件名
④ LOG_LEVEL 默认: 'DEBUG',log的最低级别
⑤ LOG_STDOUT 默认: False 如果为 True,进程所有的标准输出(及错误)将会被重定向到log中。例如,执行 print "hello" ,其将会在Scrapy log中显示。

三、 CrawlSpider爬虫案例分析

1、创建项目:scrapy startproject CrawlYouYuan

2、创建爬虫文件:scrapy genspider -t crawl youyuan youyuan.com

3、项目文件分析

items.py

模型类
import scrapy
class CrawlyouyuanItem(scrapy.Item):
  # 用户名
  username = scrapy.Field()
  # 年龄
  age = scrapy.Field()
  # 头像图片的链接
  header_url = scrapy.Field()
  # 相册图片的链接
  images_url = scrapy.Field()
  # 内心独白
  content = scrapy.Field()
  # 籍贯
  place_from = scrapy.Field()
  # 学历
  education = scrapy.Field()
  # 兴趣爱好
  hobby = scrapy.Field()
  # 个人主页
  source_url = scrapy.Field()
  # 数据来源网站
  sourec = scrapy.Field()
  # utc 时间
  time = scrapy.Field()
  # 爬虫名
  spidername = scrapy.Field()

youyuan.py

爬虫文件
# -*- coding: utf-8 -*-
import scrapy
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule
from CrawlYouYuan.items import CrawlyouyuanItem
import re
class YouyuanSpider(CrawlSpider):
  name = 'youyuan'
  allowed_domains = ['youyuan.com']
  start_urls = ['http://www.youyuan.com/find/beijing/mm18-25/advance-0-0-0-0-0-0-0/p1/']
  # 自动生成的文件不需要改东西,只需要添加rules文件里面Rule角色就可以
  # 每一页匹配规则
  page_links = LinkExtractor(allow=(r"youyuan.com/find/beijing/mm18-25/advance-0-0-0-0-0-0-0/p\d+/"))
  # 每个人个人主页匹配规则
  profile_links = LinkExtractor(allow=(r"youyuan.com/\d+-profile/"))
  rules = (
    # 没有回调函数,说明follow是True
    Rule(page_links),
    # 有回调函数,说明follow是False
    Rule(profile_links, callback='parse_item', follow=True),
  )

  def parse_item(self, response):
    item = CrawlyouyuanItem()

    item['username'] = self.get_username(response)
    # 年龄
    item['age'] = self.get_age(response)
    # 头像图片的链接
    item['header_url'] = self.get_header_url(response)
    # 相册图片的链接
    item['images_url'] = self.get_images_url(response)
    # 内心独白
    item['content'] = self.get_content(response)
    # 籍贯
    item['place_from'] = self.get_place_from(response)
    # 学历
    item['education'] = self.get_education(response)
    # 兴趣爱好
    item['hobby'] = self.get_hobby(response)
    # 个人主页
    item['source_url'] = response.url
    # 数据来源网站
    item['sourec'] = "youyuan"

    yield item

  def get_username(self, response):
    username = response.xpath("//dl[@class='personal_cen']//div[@class='main']/strong/text()").extract()
    if len(username):
      username = username[0]
    else:
      username = "NULL"
    return username.strip()

  def get_age(self, response):
    age = response.xpath("//dl[@class='personal_cen']//dd/p/text()").extract()
    if len(age):
      age = re.findall(u"\d+岁", age[0])[0]
    else:
      age = "NULL"
    return age.strip()

  def get_header_url(self, response):
    header_url = response.xpath("//dl[@class='personal_cen']/dt/img/@src").extract()
    if len(header_url):
      header_url = header_url[0]
    else:
      header_url = "NULL"
    return header_url.strip()

  def get_images_url(self, response):
    images_url = response.xpath("//div[@class='ph_show']/ul/li/a/img/@src").extract()
    if len(images_url):
      images_url = ", ".join(images_url)
    else:
      images_url = "NULL"
    return images_url

  def get_content(self, response):
    content = response.xpath("//div[@class='pre_data']/ul/li/p/text()").extract()
    if len(content):
      content = content[0]
    else:
      content = "NULL"
    return content.strip()

  def get_place_from(self, response):
    place_from = response.xpath("//div[@class='pre_data']/ul/li[2]//ol[1]/li[1]/span/text()").extract()
    if len(place_from):
      place_from = place_from[0]
    else:
      place_from = "NULL"
    return place_from.strip()

  def get_education(self, response):
    education = response.xpath("//div[@class='pre_data']/ul/li[3]//ol[2]/li[2]/span/text()").extract()
    if len(education):
      education = education[0]
    else:
      education = "NULL"
    return education.strip()

  def get_hobby(self, response):
    hobby = response.xpath("//dl[@class='personal_cen']//ol/li/text()").extract()
    if len(hobby):
      hobby = ",".join(hobby).replace(" ", "")
    else:
      hobby = "NULL"
    return hobby.strip()

pipelines.py

管道文件
import json
import codecs
class CrawlyouyuanPipeline(object):

  def __init__(self):
    self.filename = codecs.open('content.json', 'w', encoding='utf-8')

  def process_item(self, item, spider):
    html = json.dumps(dict(item), ensure_ascii=False)
    self.filename.write(html + '\n')
    return item

  def spider_closed(self, spider):
    self.filename.close()

settings.py

BOT_NAME = 'CrawlYouYuan'
SPIDER_MODULES = ['CrawlYouYuan.spiders']
NEWSPIDER_MODULE = 'CrawlYouYuan.spiders'
# Crawl responsibly by identifying yourself (and your website) on the user-agent
USER_AGENT = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.13; rv:56.0)'
# Obey robots.txt rules
ROBOTSTXT_OBEY = True
ITEM_PIPELINES = {
  'CrawlYouYuan.pipelines.CrawlyouyuanPipeline': 300,
}

begin.py

from scrapy import cmdline
cmdline.execute('scrapy crawl youyuan'.split())

在运行程序之前需要使Scrapy版本和Twisted版本相吻合,设置如下

这次分享详细介绍了使用Scrapy框架爬虫的具体步骤,并同时编写爬虫案例进行分析,很好的诠释了Scrapy框架爬取数据的方便性和易懂性,下篇文章我会分享下Scrapy分布式爬取网站,让我们一起学习,一起探讨爬虫技术。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

(0)

相关推荐

  • 使用Python的Scrapy框架编写web爬虫的简单示例

    在这个教材中,我们假定你已经安装了Scrapy.假如你没有安装,你可以参考这个安装指南. 我们将会用开放目录项目(dmoz)作为我们例子去抓取. 这个教材将会带你走过下面这几个方面: 创造一个新的Scrapy项目 定义您将提取的Item 编写一个蜘蛛去抓取网站并提取Items. 编写一个Item Pipeline用来存储提出出来的Items Scrapy由Python写成.假如你刚刚接触Python这门语言,你可能想要了解这门语言起,怎么最好的利用这门语言.假如你已经熟悉其它类似的语言,想要快速

  • Python实现从脚本里运行scrapy的方法

    本文实例讲述了Python实现从脚本里运行scrapy的方法.分享给大家供大家参考.具体如下: 复制代码 代码如下: #!/usr/bin/python import os os.environ.setdefault('SCRAPY_SETTINGS_MODULE', 'project.settings') #Must be at the top before other imports from scrapy import log, signals, project from scrapy.x

  • 使用scrapy实现爬网站例子和实现网络爬虫(蜘蛛)的步骤

    复制代码 代码如下: #!/usr/bin/env python# -*- coding: utf-8 -*- from scrapy.contrib.spiders import CrawlSpider, Rulefrom scrapy.contrib.linkextractors.sgml import SgmlLinkExtractorfrom scrapy.selector import Selector from cnbeta.items import CnbetaItemclass

  • 讲解Python的Scrapy爬虫框架使用代理进行采集的方法

    1.在Scrapy工程下新建"middlewares.py" # Importing base64 library because we'll need it ONLY in case if the proxy we are going to use requires authentication import base64 # Start your middleware class class ProxyMiddleware(object): # overwrite process

  • 零基础写python爬虫之使用Scrapy框架编写爬虫

    网络爬虫,是在网上进行数据抓取的程序,使用它能够抓取特定网页的HTML数据.虽然我们利用一些库开发一个爬虫程序,但是使用框架可以大大提高效率,缩短开发时间.Scrapy是一个使用Python编写的,轻量级的,简单轻巧,并且使用起来非常的方便.使用Scrapy可以很方便的完成网上数据的采集工作,它为我们完成了大量的工作,而不需要自己费大力气去开发. 首先先要回答一个问题. 问:把网站装进爬虫里,总共分几步? 答案很简单,四步: 新建项目 (Project):新建一个新的爬虫项目 明确目标(Item

  • python使用scrapy解析js示例

    复制代码 代码如下: from selenium import selenium class MySpider(CrawlSpider):    name = 'cnbeta'    allowed_domains = ['cnbeta.com']    start_urls = ['http://www.jb51.net'] rules = (        # Extract links matching 'category.php' (but not matching 'subsectio

  • 在Linux系统上安装Python的Scrapy框架的教程

    这是一款提取网站数据的开源工具.Scrapy框架用Python开发而成,它使抓取工作又快又简单,且可扩展.我们已经在virtual box中创建一台虚拟机(VM)并且在上面安装了Ubuntu 14.04 LTS. 安装 Scrapy Scrapy依赖于Python.开发库和pip.Python最新的版本已经在Ubuntu上预装了.因此我们在安装Scrapy之前只需安装pip和python开发库就可以了. pip是作为python包索引器easy_install的替代品,用于安装和管理Python

  • Python爬虫框架Scrapy安装使用步骤

    一.爬虫框架Scarpy简介Scrapy 是一个快速的高层次的屏幕抓取和网页爬虫框架,爬取网站,从网站页面得到结构化的数据,它有着广泛的用途,从数据挖掘到监测和自动测试,Scrapy完全用Python实现,完全开源,代码托管在Github上,可运行在Linux,Windows,Mac和BSD平台上,基于Twisted的异步网络库来处理网络通讯,用户只需要定制开发几个模块就可以轻松的实现一个爬虫,用来抓取网页内容以及各种图片. 二.Scrapy安装指南 我们的安装步骤假设你已经安装一下内容:<1>

  • Scrapy框架CrawlSpiders的介绍以及使用详解

    在Scrapy基础--Spider中,我简要地说了一下Spider类.Spider基本上能做很多事情了,但是如果你想爬取知乎或者是简书全站的话,你可能需要一个更强大的武器.CrawlSpider基于Spider,但是可以说是为全站爬取而生. CrawlSpiders是Spider的派生类,Spider类的设计原则是只爬取start_url列表中的网页,而CrawlSpider类定义了一些规则(rule)来提供跟进link的方便的机制,从爬取的网页中获取link并继续爬取的工作更适合. 一.我们先

  • Python:Scrapy框架中Item Pipeline组件使用详解

    Item Pipeline简介 Item管道的主要责任是负责处理有蜘蛛从网页中抽取的Item,他的主要任务是清晰.验证和存储数据. 当页面被蜘蛛解析后,将被发送到Item管道,并经过几个特定的次序处理数据. 每个Item管道的组件都是有一个简单的方法组成的Python类. 他们获取了Item并执行他们的方法,同时他们还需要确定的是是否需要在Item管道中继续执行下一步或是直接丢弃掉不处理. Item管道通常执行的过程有 清理HTML数据 验证解析到的数据(检查Item是否包含必要的字段) 检查是

  • YII框架中搜索分页jQuery写法详解

    控制层 use frontend\models\StudUser; use yii\data\Pagination; use yii\db\Query; /** * 查询 * */ public function actionSearch() { //接值 $where=Yii::$app->request->get(); //实例化query $query=new Query(); $query->from('stud_user'); //判断 if(isset($where['sex

  • python框架django项目部署相关知识详解

    这篇文章主要介绍了python框架django项目部署相关知识详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 一:项目部署的框架 nginx和uWSGI在生产服务器上进行的部署 二:什么是nginx? nginx是一个web服务器. 什么是web服务器? web服务器则主要是让客户可以通过浏览器进行访问,处理HTML文件,css文件,js文件,图片等资源.web服务器一般要处理静态文件.对接服务器. 什么是静态文件? css,js,html

  • vue框架中props的typescript用法详解

    什么是typescript typescript 为 javaScript的超集,这意味着它支持所有都JavaScript都语法.它很像JavaScript都强类型版本,除此之外,它还有一些扩展的语法,如interface/module等. typescript 在编译期会去掉类型和特有语法,生成纯粹的JavaScript. Typescript 5年内的热度随时间变化的趋势,整体呈现一个上升的趋势.也说明ts越来越️受大家的关注了. 在vue中使用typescript时,需要引入vue-pro

  • Spring框架构造注入type属性实例详解

    这篇文章主要介绍了Spring框架构造注入type属性实例详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 进行测试,验证一个问题,废话不多说了,上代码进行比较 package service.impl; import service.UserService; import dao.UserDao; import entity.User; /** * 用户业务类,实现对User功能的业务管理 */ public class UserServi

  • Python+appium框架原生代码实现App自动化测试详解

    step1:首先介绍下python+appium的框架结构,如下截图所示 (1):apk目录主要放置待测app的apk资源: (2):config目录主要放置配置文件信息,包含:数据库连接配置.UI自动化脚本中所需的页面元素信息及app启动信息.自动化报告邮件发送配置信息.接口请求的对应的url信息等[大家可根据待测app的功能添加或减少配置文件信息]. (3):report目录主要放置测试完成后生成的测试报告信息: (4):src目录下包含的目录如下 common目录:app启动方法的封装文件

  • 使用idea创建web框架和配置struts的方法详解

    如何用idea创建web框架和配置struts 创建好一个project右键project,选择第二项 选中Web Application,然后点击OK 创建文件夹名为lib(用来存放jar包)和classes(用来存放输出文件) 在官网下载struts,把jar放入lib中,然后右键lib,选择 add as library(导入成功) 点击file-project structure-modules-path 把两个路径都改为web文件夹下面的classes(刚创建的) 总结 到此这篇关于使

  • SpringMVC框架整合Junit进行单元测试(案例详解)

    本文主要介绍在SpringMVC框架整合Junit框架进行单元测试.闲话少述,让我们直入主题. 系统环境 软件 版本 spring-webmvc 4.3.6.RELEASE spring-test 4.3.6.RELEASE junit 4.12 引入依赖 <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</ver

  • Java集合框架之List ArrayList LinkedList使用详解刨析

    目录 1. List 1.1 List 的常见方法 1.2 代码示例 2. ArrayList 2.1 介绍 2.2 ArrayList 的构造方法 2.3 ArrayList 底层数组的大小 3. LinkedList 3.1 介绍 3.2 LinkedList 的构造方法 4. 练习题 5. 扑克牌小游戏 1. List 1.1 List 的常见方法 方法 描述 boolean add(E e) 尾插 e void add(int index, E element) 将 e 插入到 inde

随机推荐