如果想要通过爬虫程序去爬取某个网站全部页码或者部分页码的数据的话,有几种实现方法呢

  1, 基于scrapy框架中的spider的递归爬取进行实现(Request递归毁掉parse方法)

  2, 基于CrawlSpider的自动爬取,这种方法更加简洁和高效,更推荐使用

 

一, 简介

CrawlScrapy其实是spider的一个子类,除了继承到spider的特性和功能外,还派生除了其自己独有的更加强大的特性和功能,其中最显著的功能就是"LinkExtractors链接提取器",spider是所有爬虫的基类,其设计原则只是为了爬取start_urls列表中的网页,二从爬取到的网页中提取出的url进行继续的爬取工作使用CrawlSpider更合适

 

二, 使用

1, 创建scrapy工程 :

scrapy startproject projectName

2, cd  projectName 进入文件

 创建爬虫文件:

scrapy genspider -t crawl spiderName www.xxx.com
# 此指令对比之前的创建爬虫文件的指令,多了"-t crawl",表示创建的爬虫文件是基于CrawlSpider这个类的

 

3, 观察生成的爬虫文件

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


class ChoutiSpider(CrawlSpider):
    name = 'chouti'
    # allowed_domains = ['www.xxx.com']
    start_urls = ['https://dig.chouti.com/r/scoff/hot/1']
    
    
    # rules其作用是定义”提取动作“。在rules中可以包含一个或多个Rule对象,一个Rule对象表示一种提取规则
    rules = (
        #Rule规则解析器:将链接提取器提取到的连接所对应的页面数据进行指定形式的解析
        # LinkExtractor连接提取器:
        # allow:表示的就是链接提取器提取连接的规则(正则)
        # callback : 指定规则解析器解析数据的规则(回调函数)
        # follow=True让连接提取器继续作用到链接提取器提取到的连接所对应的页面中
        Rule(LinkExtractor(allow=r'/r/scoff/hot/\d+'), callback='parse_item', follow=True )
    
    def parse_item(self, response):
        print(response)    



# LinkExtractor中的参数
    # allow=r'Items/',# 满足括号中“正则表达式”的值会被提取,如果为空,则全部匹配。    
    #deny=xxx,  # 满足正则表达式的则不会被提取。
    #restrict_xpaths=xxx, # 满足xpath表达式的值会被提取
    # restrict_css=xxx, # 满足css表达式的值会被提取
    #deny_domains=xxx, # 不会被提取的链接的domains
 

 

代码示例 : 爬取抽屉段子

爬虫文件:

 1 # -*- coding: utf-8 -*-
 2 import scrapy
 3 from scrapy.linkextractors import LinkExtractor
 4 from scrapy.spiders import CrawlSpider, Rule
 5 
 6 
 7 class ChoutiSpider(CrawlSpider):
 8     name = 'chouti'
 9     # allowed_domains = ['www.xxx.com']
10     start_urls = ['https://dig.chouti.com/r/scoff/hot/1']
11     
12     #连接提取器:
13     #allow:表示的就是链接提取器提取连接的规则(正则)
14     link = LinkExtractor(allow=r'/r/scoff/hot/\d+')
15     
16     rules = (
17         #规则解析器:将链接提取器提取到的连接所对应的页面数据进行指定形式的解析
18         Rule(link, callback='parse_item', follow=True),
19         # 让连接提取器继续作用到链接提取器提取到的连接所对应的页面中
20     )
21     
22     def parse_item(self, response):
23         print(response)
View Code