念念不忘,必有回响!繁华似锦觅安宁,淡云流水度此生--------潇洒若梦&&浮生执铭
潇洒浮生
因为你 我愿意热爱整个世界

CrawlSpider

问题:如果我们想要对某一个网站的全站数据进行爬取?

解决方案:

  1. 手动请求的发送
  2. CrawlSpider(推荐)

CrawlSpider概念:CrawlSpider其实就是Spider的一个子类。CrawlSpider功能更加强大(链接提取器,规则解析器)。

 

代码流程:

  1. 创建一个基于CrawlSpider的爬虫文件

    a) scrapy genspider  –t  crawl 爬虫名称  起始url

编写爬虫文件

 

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


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

    #实例化了一个链接提取器对象
    #链接提取器:用来提取指定的链接(url)
    #allow参数:赋值一个正则表达式
    #链接提取器就可以根据正则表达式在页面中提取指定的链接
    #提取到的链接会全部交给规则解析器
    link = LinkExtractor(allow=r'/all/hot/recent/\d+')
    rules = (
        #实例化了一个规则解析器对象
        #规则解析器接受了链接提取器发送的链接后,就会对这些链接发起请求,获取链接对应的页面内容,就会根据指定的规则对页面内容中指定的数据值进行解析
        #callback:指定一个解析规则(方法/函数)
        #follow:是否将链接提取器继续作用到连接提取器提取出的链接所表示的页面数据中
        Rule(link, callback='parse_item', follow=True),
    )

    def parse_item(self, response):
        print(response)

 

配置文件ok后,就可以执行了

 值得注意的是链接提取器里面的规则是依照页码的规律来的,用正则表示这些页面链接的特点

posted on 2018-11-28 21:51  潇洒浮生  阅读(148)  评论(0编辑  收藏  举报

levels of contents