爬虫系列---scrapy全栈数据爬取框架(Crawlspider)

一 简介

  crawlspider 是Spider的一个子类,除了继承spider的功能特性外,还派生了自己更加强大的功能。

  LinkExtractors链接提取器,Rule规则解析器。

二 强大的链接提取器和规则解析器

1 LinkExtractor 链接提取器 

    LinkExtractor(

         allow=r'Items/',# 满足括号中“正则表达式”的值会被提取,如果为空,则全部匹配。

         deny=xxx,  # 满足正则表达式的则不会被提取。

         restrict_xpaths=xxx, # 满足xpath表达式的值会被提取

         restrict_css=xxx, # 满足css表达式的值会被提取

         deny_domains=xxx, # 不会被提取的链接的domains。 

    )


作用:提取response中符合规则的链接

2 Rule:规则解析器

Rule(linkExtractor(allow=r'Items/'),callback='parse_item',follow=True)
-参数介绍
  参数1:制定链接提取器
  参数2:制定规则解析器解析数据的规则(回调函数)
  参数3:是否允许链接提取器继续作用到已经提取到的链接网页上提取新的链接,
     默认是True,即继续提取。

3 rules=()

制定不同的规则的解析器。一个Rule,一种提取规则。

三 CrawlSpider整体流程

  1. 爬取文件首先根据起始url,获取改url的网页内容;
  2. 链接提取器会根据指定提取规则将步骤1中网页内容中的链接进行提取;
  3. 规则解析器回根据指定解析规则将链接中的网页内容根据制定规则进行解析;
  4. 将解析数据封装到item中,然后提交给管道进行持久化存储。

四 实战抽屉全站爬取

  •  1 创建项目
scrapy start project ChouTi
  • 2 创建爬虫文件
cd Chouti

scrapy genspider -t crawl choti chouti.com
  • 3 爬虫文件 chouti.py
# -*- coding: utf-8 -*-
import scrapy
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule
from ChouTi.items import ChoutiItem
#LinkExtractor:链接提取器
#Rule:规则解析器

class ChoutiSpider(CrawlSpider):
    name = 'chouti'
    # allowed_domains = ['xxx.com']
    start_urls = ['https://dig.chouti.com/r/scoff/hot/1']

    link=LinkExtractor(allow=r'/r/scoff/hot/d+')
    rules = (
        Rule(link, callback='parse_item', follow=True),
    )

    def parse_item(self, response):
        # print(response)
        div_list=response.xpath('//div[@id="content-list"]/div')
        for div in div_list:
            content=div.xpath('.//div[@class="news-content"]/div[1]/a[1]/text()').extract_first().strip()
            author=div.xpath('.//div[@class="part2"]/a[4]//text()').extract_first()
            author="".join(author)
            item=ChoutiItem()
            item['author']=author
            item['content']=content
            yield item
注意:
 
多链接解析器书写方式;


class ChoutiSpider(CrawlSpider):
    name = 'chouti'
    # allowed_domains = ['xxx.com']
    start_urls = ['https://dig.chouti.com/r/scoff/hot/1']

    link=LinkExtractor(allow=r'/r/scoff/hot/d+')
    link2=LinkExtractor(allow='^/text/$') #增加特定页面提取规则
    rules = (
        Rule(link, callback='parse_item', follow=True),
        Rule(link2, callback='parse_item', follow=True),#允许添加多个规则
    )    

4 items.py

import scrapy


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

5 pipelines.py

import pymongo

class ChoutiPipeline(object):
    conn=None

    def open_spider(self,spider):
        self.conn=pymongo.MongoClient(host='127.0.0.1',port=27017)
    def process_item(self, item, spider):
        # print(item)
        self.conn.spider.chouti.insert(item.__dict__)
        return item

6 settings.py

USER_AGENT = 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.119 Safari/537.36'

ROBOTSTXT_OBEY = False

ITEM_PIPELINES = {
   'ChouTi.pipelines.ChoutiPipeline': 300,
}
原文地址:https://www.cnblogs.com/angle6-liu/p/10488453.html