1. 程式人生 > >爬蟲Scrapy框架-Crawlspider鏈接提取器與規則解析器

爬蟲Scrapy框架-Crawlspider鏈接提取器與規則解析器

一個 htm turn 創建 for tin Coding lines spi

一:Crawlspider簡介

    CrawlSpider其實是Spider的一個子類,除了繼承到Spider的特性和功能外,還派生除了其自己獨有的更加強大的特性和功能。其中最顯著的功能就是”LinkExtractors鏈接提取器“。Spider是所有爬蟲的基類,其設計原則只是為了爬取start_url列表中網頁,而從爬取到的網頁中提取出的url進行繼續的爬取工作使用CrawlSpider更合適。

二:Crawlspider使用

實例:爬取https://www.qiushibaike.com/主頁帖子作者以及內容

技術分享圖片

1.創建scrapy工程

技術分享圖片

2.創建爬蟲文件

技術分享圖片

註意:對比以前的指令多了 "-t crawl

",表示創建的爬蟲文件是基於CrawlSpider這個類的,而不再是Spider這個基類。

3.生成的目錄結構如下:

技術分享圖片

CrawlDemo.py爬蟲文件設置:

  LinkExtractor:顧名思義,鏈接提取器。
  Rule : 規則解析器。根據鏈接提取器中提取到的鏈接,根據指定規則提取解析器鏈接網頁中的內容。

  Rule參數介紹:

    參數1:指定鏈接提取器

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

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

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

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

from crawlPro.items import CrawlproItem
class CrawldemoSpider(CrawlSpider):
    name = crawlDemo
    # allowed_domains = [‘www.qiushibaike.com‘]
    start_urls = [
http://www.qiushibaike.com/] #rules元祖中存放的是不同規則解析器(封裝好了某種解析規則) rules = ( # Rule: 規則解析器,可以將連接提取器提取到的所有連接表示的頁面進行指定規則(有中間的回調函數決定)的解析 #LinkBxtractor:連接提取器,會去上面起始url響應回來的頁面中,提取指定的url Rule(LinkExtractor(allow=r/8hr/page/\d+), callback=parse_item, follow=True), #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 divs=response.xpath(//div[@id="content-left"]/div) for div in divs: item=CrawlproItem() #提取糗百中段子的作者 item[author] = div.xpath(./div[@class="author clearfix"]/a[2]/h2/text()).extract_first().strip(\n) # 提取糗百中段子的內容 item[content] = div.xpath(.//div[@class="content"]/span/text()).extract_first().strip(\n) yield item #將item提交到管道

item.py文件設置:

# -*- 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 CrawlproItem(scrapy.Item):
    # define the fields for your item here like:
    # name = scrapy.Field()
    author=scrapy.Field()
    content=scrapy.Field()

pipelines.py管道文件設置:

# -*- 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 CrawlproPipeline(object):
    def __init__(self):
        self.fp = None


    def open_spider(self,spider):
        print(開始爬蟲)
        self.fp = open(./data.txt,w,encoding=utf-8)

    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()

爬蟲Scrapy框架-Crawlspider鏈接提取器與規則解析器