CrawlSpider

 

CrawlSpider簡介

CrawlSpider實際上是Spider的一個子類,除了繼承到Spider的特性和功能外,
還派生除了其本身獨有的更增強大的特性和功能。
其中最顯著的功能就是」LinkExtractors連接提取器「。
Spider是全部爬蟲的基類,
其設計原則只是爲了爬取start_url列表中網頁,
而從爬取到的網頁中提取出的url進行繼續的爬取工做使用CrawlSpider更合適。

 

CrawlSpider使用

- 基本指令:css

  - 建立scrapy工程:scrapy startproject projectNamehtml

  - 建立爬蟲文件:scrapy genspider -t crawl spiderName www.xxx.com正則表達式

    - 指令對比之前的指令多了 "-t crawl",表示建立的爬蟲文件是基於CrawlSpider這個類的,而再也不是Spider這個基類。dom

  - 生成的爬蟲文件的源碼:scrapy

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

# 導入CrawlSpider相關模塊
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule


# 表示該爬蟲程序是基於CrawlSpider類的
class ChoutidemoSpider(CrawlSpider):
name = 'choutiDemo'
#allowed_domains = ['www.chouti.com']
start_urls = ['http://www.chouti.com/']

rules = (
Rule(LinkExtractor(allow=r'Items/'), callback='parse_item', follow=True),
)

def parse_item(self, response):
i = {}
#i['domain_id'] = response.xpath('//input[@id="sid"]/@value').extract()
#i['name'] = response.xpath('//div[@id="name"]').extract()
#i['description'] = response.xpath('//div[@id="description"]').extract()
return i

 

- 爬蟲文件簡單示例ide

# -*- coding: utf-8 -*-
import scrapy
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule


class CrawldemoSpider(CrawlSpider):
    name = 'qiubai'
    #allowed_domains = ['www.qiushibaike.com']
    start_urls = ['https://www.qiushibaike.com/pic/']

    #鏈接提取器:會去起始url響應回來的頁面中提取指定的url
    link = LinkExtractor(allow=r'/pic/page/\d+\?') #s=爲隨機數
    link1 = LinkExtractor(allow=r'/pic/$')#爬取第一頁
    #rules元組中存放的是不一樣的規則解析器(封裝好了某種解析規則)
    rules = (
        #規則解析器:能夠將鏈接提取器提取到的全部鏈接表示的頁面進行指定規則(回調函數)的解析
        Rule(link, callback='parse_item', follow=True),
        Rule(link1, callback='parse_item', follow=True),
    )

    def parse_item(self, response):
        print(response)
爬蟲文件簡單示例

 

- 解析方法:函數

  CrawlSpider類和Spider類的最大不一樣是CrawlSpider多了一個rules屬性,其做用是定義」提取動做「。在rules中能夠包含一個或多個Rule對象,在Rule對象中包含了LinkExtractor對象。post

 

- LinkExtractor:連接提取器。url

LinkExtractor(

  allow = r'Items/',  # 知足括號中「正則表達式」的值會被提取,若是爲空,則所有匹配。
  deny = xxx,  # 知足正則表達式的則不會被提取。


  restrict_xpaths = xxx,  # 知足xpath表達式的值會被提取
  restrict_css = xxx,  # 知足css表達式的值會被提取
  deny_domains = xxx,  # 不會被提取的連接的domains。 

)

  - 做用:提取response中符合規則的連接。spa

 

- Rule : 規則解析器。根據連接提取器中提取到的連接,根據指定規則提取解析器連接網頁中的內容。

  Rule(LinkExtractor(allow=r'Items/'), callback='parse_item', follow=True)

  - 參數介紹:

      參數1:指定連接提取器

      參數2:指定規則解析器解析數據的規則(回調函數)

      參數3:是否將連接提取器繼續做用到連接提取器提取出的連接網頁中。當callback爲None,參數3的默認值爲true

  - rules=( ):指定不一樣規則解析器。一個Rule對象表示一種提取規則。

 

- CrawlSpider總體爬取流程:

    a)爬蟲文件首先根據起始url,獲取該url的網頁內容

    b)連接提取器會根據指定提取規則將步驟a中網頁內容中的連接進行提取

    c)規則解析器會根據指定解析規則將連接提取器中提取到的連接中的網頁內容根據指定的規則進行解析

    d)將解析數據封裝到item中,而後提交給管道進行持久化存儲

 

- 簡單代碼實戰應用:

  - 爬取糗事百科糗圖板塊的全部頁碼數據:

  - 爬蟲文件:

# -*- coding: utf-8 -*-
import scrapy
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule
from qiubaiBycrawl.items import QiubaibycrawlItem
import re
class QiubaitestSpider(CrawlSpider):
    name = 'qiubaiTest'
    #起始url
    start_urls = ['http://www.qiushibaike.com/']

    #定義連接提取器,且指定其提取規則
    page_link = LinkExtractor(allow=r'/8hr/page/\d+/')
    
    rules = (
        #定義規則解析器,且指定解析規則經過callback回調函數
        Rule(page_link, callback='parse_item', follow=True),
    )

    #自定義規則解析器的解析規則函數
    def parse_item(self, response):
        div_list = response.xpath('//div[@id="content-left"]/div')
        
        for div in div_list:
            #定義item
            item = QiubaibycrawlItem()
            #根據xpath表達式提取糗百中段子的做者
            item['author'] = div.xpath('./div/a[2]/h2/text()').extract_first().strip('\n')
            #根據xpath表達式提取糗百中段子的內容
            item['content'] = div.xpath('.//div[@class="content"]/span/text()').extract_first().strip('\n')

            yield item #將item提交至管道

 

   - item文件:

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

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

import scrapy


class QiubaibycrawlItem(scrapy.Item):
    # define the fields for your item here like:
    # name = scrapy.Field()
    author = scrapy.Field() #做者
    content = scrapy.Field() #內容

 

- 管道文件:

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

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

class QiubaibycrawlPipeline(object):
    
    def __init__(self):
        self.fp = None
        
    def open_spider(self,spider):
        print('開始爬蟲')
        self.fp = open('./data.txt','w')
        
    def process_item(self, item, spider):
        #將爬蟲文件提交的item寫入文件進行持久化存儲
        self.fp.write(item['author']+':'+item['content']+'\n')
        return item
    
    def close_spider(self,spider):
        print('結束爬蟲')
        self.fp.close()
相關文章
相關標籤/搜索