博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Pyhton网络爬虫之CrawlSpider
阅读量:4593 次
发布时间:2019-06-09

本文共 3807 字,大约阅读时间需要 12 分钟。

一、什么是CrawlSpider?

在学习CrawlSpider之前如果我们想爬取某网站前100页的内容的话,我们可以使用的方法是通过Request模块手动发起请求,递归调用parse方法,写起来非常麻烦,效率不高,CrawlSpider其实是Spider的一个子类,除了继承到Spider的特性和功能外,还派生除了其自己独有的更加强大的特性和功能。其中最显著的功能就是”LinkExtractors链接提取器“。Spider是所有爬虫的基类,其设计原则只是为了爬取start_url列表中网页,而从爬取到的网页中提取出的url进行继续的爬取工作使用CrawlSpider更合适。

二、CrawlSpider使用

#1.创建scrapy工程:scrapy startproject projectName#2.创建爬虫文件:scrapy genspider -t crawl spiderName www.xxx.com#--此指令对比以前的指令多了 "-t crawl",表示创建的爬虫文件是基于CrawlSpider这个类的,而不再是Spider这个基类。#3.观察生成的爬虫文件# -*- coding: utf-8 -*-import scrapyfrom scrapy.linkextractors import LinkExtractorfrom scrapy.spiders import CrawlSpider, Ruleclass 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):        item = {}        #item['domain_id'] = response.xpath('//input[@id="sid"]/@value').extract()        #item['name'] = response.xpath('//div[@id="name"]').extract()        #item['description'] = response.xpath('//div[@id="description"]').extract()        return item

CrawlSpider类和Spider类的最大不同是CrawlSpider多了一个rules属性,其作用是定义”提取动

作“。在rules中可以包含一个或多个Rule对象,在Rule对象中包含了LinkExtractor对象。

  • LinkExtractor顾名思义,链接提取器。
LinkExtractor(  allow=r'Items/',# 满足括号中“正则表达式”的值会被提取,如果为空,则全部匹配。   deny=xxx,  # 满足正则表达式的则不会被提取。    restrict_xpaths=xxx, # 满足xpath表达式的值会被提取   restrict_css=xxx, # 满足css表达式的值会被提取   deny_domains=xxx, # 不会被提取的链接的domains。     )    # 作用:提取response中符合规则的链接。
  • Rule : 规则解析器。根据链接提取器中提取到的链接,根据指定规则提取解析器链接网页中的内容。(会自主对每一个提取到的url发起请求)
Rule(LinkExtractor(allow=r'Items/'), callback='parse_item', follow=True)
- 参数介绍:  参数1:指定链接提取器  参数2:指定规则解析器解析数据的规则(回调函数)  参数3:是否将链接提取器继续作用到链接提取器提取出的链接网页中。参数3的默认值为true。
  • rules=( ):指定不同规则解析器。一个Rule对象表示一种提取规则。

CrawlSpider整体爬取流程:

a)爬虫文件首先根据起始url,获取该url的网页内容b)链接提取器会根据指定提取规则将步骤a中网页内容中的链接进行提取c)规则解析器会根据指定解析规则将链接提取器中提取到的链接中的网页内容根据指定的规则进行解析d)将解析数据封装到item中,然后提交给管道进行持久化存储

实战应用

# -*- coding: utf-8 -*-import scrapyfrom scrapy.linkextractors import LinkExtractorfrom scrapy.spiders import CrawlSpider, Ruleclass 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):        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提交至管道
import scrapyclass QiubaibycrawlItem(scrapy.Item):    # define the fields for your item here like:    # name = scrapy.Field()    author = scrapy.Field() #作者    content = scrapy.Field() #内容
item文件:
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()
管道文件

 

转载于:https://www.cnblogs.com/fengchong/p/10479360.html

你可能感兴趣的文章
LeetCode 102. 二叉树的层次遍历
查看>>
CCF | 小中大
查看>>
LeetCode 589. N叉树的前序遍历
查看>>
LeetCode 145. 二叉树的后序遍历
查看>>
Java | JDK8下的ConcurrentHashMap#putValue
查看>>
LeetCode 144. 二叉树的前序遍历
查看>>
周总结
查看>>
作业13-网络java
查看>>
Qt加载lib文件
查看>>
element vuex 语音播报
查看>>
tomcat剖析(二)
查看>>
装机摸鱼日志--ubuntu16.04安装网易云音乐客户端
查看>>
eclipse中Android模拟器,DDMS看不到设备
查看>>
Flex 布局教程学习
查看>>
day11_rowid、rownum、表分类
查看>>
软件测试培训第4天
查看>>
Android:网络操作2.3等低版本正常,4.0(ICS)以上出错,换用AsyncTask异步线程get json...
查看>>
单次插入与批量插入时间对比
查看>>
python从excel读取的数据为数字时,自动加上.0转化为浮点型的解决
查看>>
IDEA 如何加上 tomcat
查看>>