Python爬虫-Scrapy框架之Spider

1、Scrapy架构图

Scrapy架构图(1)
Scrapy架构图(2)

  模块介绍:
  1)Scrapy Engine(引擎):Scrapy框架的核心部分,负责在Spider和Item Pipeline、Downloader、Scheduler中间通信、传递数据等;
  2)Spider(爬虫):发送需要爬取的链接给引擎,最后引擎把其他模块请求回来的数据再发送给爬虫,爬虫就去解析想要的数据,这个部分是我们开发者自己写的,因为要爬取哪些链接,页面中的那些数据是我们需要的,都是由程序员自己决定的;
  3)Scheduler(调度器):负责接收引擎发送过来的请求,并按照一定的方式进行排列和整理,负责调度请求的顺序等;
  4)Downloader(下载器):负责接收引擎传过来的下载请求,然后去网络上下载对应的数据再交还给引擎;
  5)Item Pipeline(管道):负责将Spider(爬虫)传递过来的数据进行保存,具体保存在哪里,应该看开发者自己的需求;
  6)Downloader Middlewares(下载中间件):可以扩展下载器和引擎之间通信功能的中间件;
  7 )Spider Middlewares(Spider中间件):可以扩展引擎和爬虫之间通信功能的中间件。

2、安装和文档

  1)安装:通过pip install scrapy即可安装;
  2)Scrapy官方文档:http://doc.scrapy.org/en/latest
  3)Scrapy中文文档:http://scrapy-chs.readthedocs.io/zh_CN/latest/index.html

  注意:
  1)在Ubuntu上安装Scrapy之前,需要先安装以下依赖:sudo apt-get install python3 python3-dev python3-pip libxml2-dev libxslt1-dev zlib1g-dev libffi-dev libssl-dev,然后再通过pip install scrapy安装;
  2)如果在Windows系统下,提示这个错误ModuleNotFoundError: No module named 'win32api',那么使用以下命令可以解决:pip install pypiwin32

3、创建项目

  要使用Scrapy框架创建项目,需要通过命令来创建,首先进入到你想把这个项目存放的目录,然后使用命令scrapy startproject [项目名]创建即可。

D:\学习笔记\Python学习\Python_Crawler>scrapy startproject qiushibk
New Scrapy project 'qiushibk', using template directory 'c:\python38\lib\site-packages\scrapy\templates\project', created in:
    D:\学习笔记\Python学习\Python_Crawler\qiushibk

You can start your first spider with:
    cd qiushibk
    scrapy genspider example example.com
Scrapy项目目录结构

  主要文件的作用:
  1)items.py:用来存放爬虫爬取下来数据的模型;
  2)middlewares.py:用来存放各种中间件的文件;
  3)pipelines.py:用来将items的模型存储到本地磁盘中;
  4)settings.py:本爬虫的一些配置信息(比如请求头、多久发送一次请求、IP代理池等);
  5)scrapy.cfg:项目的配置文件;
  6)spiders:以后所有的爬虫,都是存放到这个里面。

  spiders/init.py文件初始内容如下:

# This package will contain the spiders of your Scrapy project
#
# Please refer to the documentation for information on how to create and manage
# your spiders.

  items.py文件初始内容如下:

# -*- coding: utf-8 -*-

# Define here the models for your scraped items
#
# See documentation in:
# https://docs.scrapy.org/en/latest/topics/items.html

import scrapy


class QiushibkItem(scrapy.Item):
    # define the fields for your item here like:
    # name = scrapy.Field()
    pass

  middlewares.py文件初始内容如下:

# -*- coding: utf-8 -*-

# Define here the models for your spider middleware
#
# See documentation in:
# https://docs.scrapy.org/en/latest/topics/spider-middleware.html

from scrapy import signals


class QiushibkSpiderMiddleware:
    # Not all methods need to be defined. If a method is not defined,
    # scrapy acts as if the spider middleware does not modify the
    # passed objects.

    @classmethod
    def from_crawler(cls, crawler):
        # This method is used by Scrapy to create your spiders.
        s = cls()
        crawler.signals.connect(s.spider_opened, signal=signals.spider_opened)
        return s

    def process_spider_input(self, response, spider):
        # Called for each response that goes through the spider
        # middleware and into the spider.

        # Should return None or raise an exception.
        return None

    def process_spider_output(self, response, result, spider):
        # Called with the results returned from the Spider, after
        # it has processed the response.

        # Must return an iterable of Request, dict or Item objects.
        for i in result:
            yield i

    def process_spider_exception(self, response, exception, spider):
        # Called when a spider or process_spider_input() method
        # (from other spider middleware) raises an exception.

        # Should return either None or an iterable of Request, dict
        # or Item objects.
        pass

    def process_start_requests(self, start_requests, spider):
        # Called with the start requests of the spider, and works
        # similarly to the process_spider_output() method, except
        # that it doesn’t have a response associated.

        # Must return only requests (not items).
        for r in start_requests:
            yield r

    def spider_opened(self, spider):
        spider.logger.info('Spider opened: %s' % spider.name)


class QiushibkDownloaderMiddleware:
    # Not all methods need to be defined. If a method is not defined,
    # scrapy acts as if the downloader middleware does not modify the
    # passed objects.

    @classmethod
    def from_crawler(cls, crawler):
        # This method is used by Scrapy to create your spiders.
        s = cls()
        crawler.signals.connect(s.spider_opened, signal=signals.spider_opened)
        return s

    def process_request(self, request, spider):
        # Called for each request that goes through the downloader
        # middleware.

        # Must either:
        # - return None: continue processing this request
        # - or return a Response object
        # - or return a Request object
        # - or raise IgnoreRequest: process_exception() methods of
        #   installed downloader middleware will be called
        return None

    def process_response(self, request, response, spider):
        # Called with the response returned from the downloader.

        # Must either;
        # - return a Response object
        # - return a Request object
        # - or raise IgnoreRequest
        return response

    def process_exception(self, request, exception, spider):
        # Called when a download handler or a process_request()
        # (from other downloader middleware) raises an exception.

        # Must either:
        # - return None: continue processing this exception
        # - return a Response object: stops process_exception() chain
        # - return a Request object: stops process_exception() chain
        pass

    def spider_opened(self, spider):
        spider.logger.info('Spider opened: %s' % spider.name)

  pipelines.py文件初始内容如下:

# -*- coding: utf-8 -*-

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html


class QiushibkPipeline:
    def process_item(self, item, spider):
        return item

  settings.py文件初始内容如下:

# -*- coding: utf-8 -*-

# Scrapy settings for qiushibk project
#
# For simplicity, this file contains only settings considered important or
# commonly used. You can find more settings consulting the documentation:
#
#     https://docs.scrapy.org/en/latest/topics/settings.html
#     https://docs.scrapy.org/en/latest/topics/downloader-middleware.html
#     https://docs.scrapy.org/en/latest/topics/spider-middleware.html

BOT_NAME = 'qiushibk'

SPIDER_MODULES = ['qiushibk.spiders']
NEWSPIDER_MODULE = 'qiushibk.spiders'


# Crawl responsibly by identifying yourself (and your website) on the user-agent
#USER_AGENT = 'qiushibk (+http://www.yourdomain.com)'

# Obey robots.txt rules
ROBOTSTXT_OBEY = True

# Configure maximum concurrent requests performed by Scrapy (default: 16)
#CONCURRENT_REQUESTS = 32

# Configure a delay for requests for the same website (default: 0)
# See https://docs.scrapy.org/en/latest/topics/settings.html#download-delay
# See also autothrottle settings and docs
#DOWNLOAD_DELAY = 3
# The download delay setting will honor only one of:
#CONCURRENT_REQUESTS_PER_DOMAIN = 16
#CONCURRENT_REQUESTS_PER_IP = 16

# Disable cookies (enabled by default)
#COOKIES_ENABLED = False

# Disable Telnet Console (enabled by default)
#TELNETCONSOLE_ENABLED = False

# Override the default request headers:
#DEFAULT_REQUEST_HEADERS = {
#   'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
#   'Accept-Language': 'en',
#}

# Enable or disable spider middlewares
# See https://docs.scrapy.org/en/latest/topics/spider-middleware.html
#SPIDER_MIDDLEWARES = {
#    'qiushibk.middlewares.QiushibkSpiderMiddleware': 543,
#}

# Enable or disable downloader middlewares
# See https://docs.scrapy.org/en/latest/topics/downloader-middleware.html
#DOWNLOADER_MIDDLEWARES = {
#    'qiushibk.middlewares.QiushibkDownloaderMiddleware': 543,
#}

# Enable or disable extensions
# See https://docs.scrapy.org/en/latest/topics/extensions.html
#EXTENSIONS = {
#    'scrapy.extensions.telnet.TelnetConsole': None,
#}

# Configure item pipelines
# See https://docs.scrapy.org/en/latest/topics/item-pipeline.html
#ITEM_PIPELINES = {
#    'qiushibk.pipelines.QiushibkPipeline': 300,
#}

# Enable and configure the AutoThrottle extension (disabled by default)
# See https://docs.scrapy.org/en/latest/topics/autothrottle.html
#AUTOTHROTTLE_ENABLED = True
# The initial download delay
#AUTOTHROTTLE_START_DELAY = 5
# The maximum download delay to be set in case of high latencies
#AUTOTHROTTLE_MAX_DELAY = 60
# The average number of requests Scrapy should be sending in parallel to
# each remote server
#AUTOTHROTTLE_TARGET_CONCURRENCY = 1.0
# Enable showing throttling stats for every response received:
#AUTOTHROTTLE_DEBUG = False

# Enable and configure HTTP caching (disabled by default)
# See https://docs.scrapy.org/en/latest/topics/downloader-middleware.html#httpcache-middleware-settings
#HTTPCACHE_ENABLED = True
#HTTPCACHE_EXPIRATION_SECS = 0
#HTTPCACHE_DIR = 'httpcache'
#HTTPCACHE_IGNORE_HTTP_CODES = []
#HTTPCACHE_STORAGE = 'scrapy.extensions.httpcache.FilesystemCacheStorage'

  scrapy.cfg文件初始内容如下:

# Automatically created by: scrapy startproject
#
# For more information about the [deploy] section see:
# https://scrapyd.readthedocs.io/en/latest/deploy.html

[settings]
default = qiushibk.settings

[deploy]
#url = http://localhost:6800/
project = qiushibk

4、创建爬虫

D:\学习笔记\Python学习\Python_Crawler>cd qiushibk
D:\学习笔记\Python学习\Python_Crawler\qiushibk>scrapy genspider qsbk "qiushibaike.com"
Created spider 'qsbk' using template 'basic' in module:
  qiushibk.spiders.qsbk

  注意:爬虫名字不能和项目名字一致。


生成qsbk.py文件

  如上图,创建了一个名为qsbk.py的爬虫文件,并且能够爬取的网页只会限制在qiushibaike.com这个域名下。
  qsbk.py文件初始内容如下:

# -*- coding: utf-8 -*-
import scrapy


class QsbkSpider(scrapy.Spider):
    name = 'qsbk'
    allowed_domains = ['qiushibaike.com']
    start_urls = ['http://qiushibaike.com/']

    def parse(self, response):
        pass

5、爬虫实例(糗事百科)

  在做一个爬虫之前,一定要记得修改settings.py中的设置,两个地方是强烈建议设置的:
  1)ROBOTSTXT_OBEY设置为False,默认是True,即遵守机器协议,那么在爬虫的时候,scrapy首先去找robots.txt文件,如果没有找到,则直接停止爬取。
  2)DEFAULT_REQUEST_HEADERS添加User-Agent,这个也是告诉服务器,我这个请求是一个正常请求,不是一个爬虫。

  说明:
  1)response是一个scrapy.http.response.html.HtmlResponse对象,可以执行xpathcss语法来提取数据;
  2)提取出来的数据,是一个Selector或者是一个SelectorList对象,如果想要获取其中的字符串,那么应该执行getall或者get方法;
  3)getall方法:获取Selector中所有的文本,返回的是一个列表;
  4)get方法:获取的是Selector中的第一个文本,返回的是一个str类型;
  5)如果数据解析回来,要传给pipeline处理,那么可以使用yield来返回,或者是收集所有的item,最后统一使用return返回;
  6)item:建议在items.py中定义好模型,以后就不要使用字典了;
  7)pipeline:这个是专门用来保存数据的,其中有三个方法是会经常用的:
  7.1)open_spider(self,spider):当爬虫被打开的时候执行;
  7.2)process_item(self,item,spider):当爬虫有item传过来的时候会被调用;
  7.3)close_spider(self,spider):当爬虫关闭的时候会被调用。
  要激活pipeline,应该在settings.py中设置ITEM_PIPELINES

  A)settings.py设置

ROBOTSTXT_OBEY = False

DOWNLOAD_DELAY = 1

DEFAULT_REQUEST_HEADERS = {
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
    'Accept-Language': 'en',
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.9 Safari/537.36',
}

ITEM_PIPELINES = {
   'qiushibk.pipelines.QiushibkPipeline': 300,
}

  B)创建start.py文件
 &esmp;在项目的根目录下创建start.py文件,并编写代码。

from scrapy import cmdline
cmdline.execute("scrapy crawl qsbk".split())

  C)qsbk.py代码如下:

# -*- coding: utf-8 -*-
import scrapy
from qiushibk.items import QiushibkItem
# from scrapy.http.response.html import HtmlResponse
# from scrapy.selector.unified import SelectorList


class QsbkSpider(scrapy.Spider):
    name = 'qsbk'
    allowed_domains = ['qiushibaike.com']
    baseDomain = "https://www.qiushibaike.com"
    start_urls = ['https://www.qiushibaike.com/text/page/1/']

    def parse(self, response):
        duanziDivs = response.xpath("//div[@class='col1 old-style-col1']/div")
        for duanziDiv in duanziDivs:
            author = duanziDiv.xpath(".//h2/text()").get().strip()
            content = duanziDiv.xpath(".//div[@class='content']//text()").getall()
            content = "".join(content).strip()
            item = QiushibkItem(author=author,content=content)
            yield item
        nextUrl = response.xpath("//ul[@class='pagination']/li[last()]/a/@href").get()
        if not nextUrl:
            return
        else:
            yield scrapy.Request(self.baseDomain+nextUrl,callback=self.parse)

  D)items.py代码如下:

# -*- coding: utf-8 -*-

# Define here the models for your scraped items
#
# See documentation in:
# https://docs.scrapy.org/en/latest/topics/items.html

import scrapy


class QiushibkItem(scrapy.Item):
    # define the fields for your item here like:
    # name = scrapy.Field()
    author = scrapy.Field()
    content = scrapy.Field()

  E)pipelines.py代码如下:

# -*- coding: utf-8 -*-

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html
import json

class QiushibkPipeline:
    def __init__(self):
        self.fp = open("duanzi.json", "w", encoding='utf-8')

    def open_spider(self,spider):
        print("爬虫开始了……")

    def process_item(self, item, spider):
        itemJson = json.dumps(dict(item), ensure_ascii=False)
        self.fp.write(itemJson+"\n")
        return item

    def close_spider(self,spider):
        self.fp.close()
        print("爬虫结束了……")

  E.1)pipelines.py优化代码(1)如下:
  保存json数据的时候,可以使用JsonItemExporter类,这个类是每次把数据添加到内存中,最后统一写入到磁盘中,好处是存储的数据是一个满足json规则的数据,坏处是如果数据量比较大,会比较耗内存。

# -*- coding: utf-8 -*-

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html

from scrapy.exporters import JsonItemExporter

class QiushibkPipeline:
    def __init__(self):
        self.fp = open("duanzi.json", "wb")
        self.exporter = JsonItemExporter(self.fp, ensure_ascii = False, encoding='utf-8')
        self.exporter.start_exporting()

    def open_spider(self,spider):
        print("爬虫开始了……")

    def process_item(self, item, spider):
        self.exporter.export_item(item)
        return item

    def close_spider(self,spider):
        self.exporter.finish_exporting()
        self.fp.close()
        print("爬虫结束了……")

  E.2)pipelines.py优化代码(2)如下:
  保存json数据的时候,可以使用JsonLinesItemExporter类,这个是每次调用export_item的时候,就把这个item存储到硬盘中,坏处是每一个字典是一行,整个文件不是一个满足json格式的文件,好处是每次处理数据的时候就直接存储到硬盘中,这样不会耗内存,数据也比较安全。

# -*- coding: utf-8 -*-

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html

from scrapy.exporters import JsonLinesItemExporter

class QiushibkPipeline:
    def __init__(self):
        self.fp = open("duanzi.json", "wb")
        self.exporter = JsonLinesItemExporter(self.fp, ensure_ascii = False, encoding='utf-8')

    def open_spider(self,spider):
        print("爬虫开始了……")

    def process_item(self, item, spider):
        self.exporter.export_item(item)
        return item

    def close_spider(self,spider):
        self.fp.close()
        print("爬虫结束了……")
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 202,905评论 5 476
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,140评论 2 379
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 149,791评论 0 335
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,483评论 1 273
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,476评论 5 364
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,516评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,905评论 3 395
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,560评论 0 256
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,778评论 1 296
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,557评论 2 319
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,635评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,338评论 4 318
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,925评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,898评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,142评论 1 259
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,818评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,347评论 2 342

推荐阅读更多精彩内容