网络爬虫之scrapy框架(CrawlSpider)
一.简介
CrawlSpider其实是Spider的一个子类,除了继承到Spider的特性和功能之外,还派生了其自己独有的更强大的特性和功能.其中最显著的功能就是"LinkExtractors链接提取器".Spider是所有爬虫的基类,其设计原则是为了爬取start_url列表中网页,从而爬取到网页中提取出的url进行继续的爬取工作使用CrawlSpiser更适合.
二.使用
1.创建scrapy工程: scrapy startproject <projectName>
2.创建爬虫文件: scrapy genspider -t crawl <spidername> www.xxx.com
- 此指令比之前多了"-t crawl",表示创建的爬虫文件是基于CrawlSpider这个类的,而不再是Spider这个基类.
3.观察生成的爬虫文件
# -*- coding: utf-8 -*-
import scrapy
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule class 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):
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
- 2,3行:导入CrawlSpider模块
- 7行:表示该爬虫程序是基于CrawlSpider类的
- 12,13,14行:表示为提取Link规则
-16行: 解析方法
CrawlSpider类和Spider类的最大不同是CrawlSpider对了一个rules属性,其作用是定义"提起动作".在rules中可以包含一个或多个Rule对象,在Rule对象中包含了LinkExtractor对象.
3.1 LinkExtractor: 顾明司仪,连接提取器.
LinkExtractor(
allow = 'Items', # 满足括号中"正则表达式"的值会被提取,如果为空,则全部匹配
deny = xxx , # 满足正则表达式的则不会被提取
restrict_xpaths = xxx ,# 满足xpath表达式的值会被提取
restrict_css = xxx, #满足css表达式的值会被提取
deny_domains = xxx, # 不会被提取的链接domains.
)
- 作用:提取response中符合规则的链接.
3.2 Rule:规则解析器.根据链接提取器中取到的链接,根据指定规则提取解析器链接网页中的内容.
Rule(LinkExtractor(allow="Items/"), callback='parse_item', follow=True)
- 参数介绍:
* 参数一: 指定链接提取器
* 参数二: 指定规则解析器解析数据的规则(回调函数)
* 参数三: 是否将链接提取器继续作用到链接提取器提取出的链接网页中.当callback为None,参数3的默认值为true.
3.3 rules=() :指定不同规则解析器.一个Rule对象表示一种提取规则.
3.4 CrawlSpider整体爬取流程:
a) 爬虫文件首先根据起始url,获取url的网页内容
b) 链接提取器会根据指定提取规则将步骤a中网页内容中的链接进行提取
c) 规则解析器会根据指定解析规则将链接提取器中提取到的链接中的网页内容根据指定的规则进行解析
d) 将解析数据封装到item中,然后提交给管道进行持久化存储
4.简单代码实战应用
4.1爬取糗事百科糗图板块的所有数据
# -*- coding: utf-8 -*-
import scrapy
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule class 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):
print(response)
4.2 爬虫文件:
# -*- coding: utf-8 -*-
import scrapy
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule
from qiubaiBycrawl.items import QiubaibycrawlItem
import re
class QiubaitestSpider(CrawlSpider):
name = 'qiubaiTest'
#起始url
start_urls = ['http://www.qiushibaike.com/'] #定义链接提取器,且指定其提取规则
page_link = LinkExtractor(allow=r'/8hr/page/\d+/') rules = (
#定义规则解析器,且指定解析规则通过callback回调函数
Rule(page_link, 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提交至管道
4.2 item文件:
# -*- 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 QiubaibycrawlItem(scrapy.Item):
# define the fields for your item here like:
# name = scrapy.Field()
author = scrapy.Field() #作者
content = scrapy.Field() #内容
4.3 管道文件:
# -*- 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 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()
网络爬虫之scrapy框架(CrawlSpider)的更多相关文章
- Python网络爬虫之Scrapy框架(CrawlSpider)
目录 Python网络爬虫之Scrapy框架(CrawlSpider) CrawlSpider使用 爬取糗事百科糗图板块的所有页码数据 Python网络爬虫之Scrapy框架(CrawlSpider) ...
- 网络爬虫值scrapy框架基础
简介 Scrapy是一个高级的Python爬虫框架,它不仅包含了爬虫的特性,还可以方便的将爬虫数据保存到csv.json等文件中. 首先我们安装Scrapy. 其可以应用在数据挖掘,信息处理或存储历史 ...
- 16.Python网络爬虫之Scrapy框架(CrawlSpider)
引入 提问:如果想要通过爬虫程序去爬取”糗百“全站数据新闻数据的话,有几种实现方法? 方法一:基于Scrapy框架中的Spider的递归爬取进行实现(Request模块递归回调parse方法). 方法 ...
- 16,Python网络爬虫之Scrapy框架(CrawlSpider)
今日概要 CrawlSpider简介 CrawlSpider使用 基于CrawlSpider爬虫文件的创建 链接提取器 规则解析器 引入 提问:如果想要通过爬虫程序去爬取”糗百“全站数据新闻数据的话, ...
- python爬虫之Scrapy框架(CrawlSpider)
提问:如果想要通过爬虫程序去爬取”糗百“全站数据新闻数据的话,有几种实现方法? 方法一:基于Scrapy框架中的Spider的递归爬去进行实现的(Request模块回调) 方法二:基于CrawlSpi ...
- 网络爬虫之scrapy框架设置代理
前戏 os.environ()简介 os.environ()可以获取到当前进程的环境变量,注意,是当前进程. 如果我们在一个程序中设置了环境变量,另一个程序是无法获取设置的那个变量的. 环境变量是以一 ...
- 网络爬虫之scrapy框架详解
twisted介绍 Twisted是用Python实现的基于事件驱动的网络引擎框架,scrapy正是依赖于twisted, 它是基于事件循环的异步非阻塞网络框架,可以实现爬虫的并发. twisted是 ...
- 爬虫之scrapy框架
解析 Scrapy解释 Scrapy是一个为了爬取网站数据,提取结构性数据而编写的应用框架. 其可以应用在数据挖掘,信息处理或存储历史数据等一系列的程序中.其最初是为了页面抓取 (更确切来说, 网络抓 ...
- 爬虫 之 scrapy框架
浏览目录 介绍 安装 项目结构及爬虫应用简介 常用命令行工具 Spiders爬虫 Selectors选择器 Item Pipeline 项目管道 Downloader Middleware下载中间件 ...
随机推荐
- input range音乐进度条
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8" ...
- Linux下汇编语言学习笔记7 ---
这是17年暑假学习Linux汇编语言的笔记记录,参考书目为清华大学出版社 Jeff Duntemann著 梁晓辉译<汇编语言基于Linux环境>的书,喜欢看原版书的同学可以看<Ass ...
- poj_2524_Ubiquitous Religions_201407211506
Ubiquitous Religions Time Limit: 5000MS Memory Limit: 65536K Total Submissions: 23390 Accepted: ...
- 洛谷——P1164 小A点菜
P1164 小A点菜 题目背景 uim神犇拿到了uoi的ra(镭牌)后,立刻拉着基友小A到了一家……餐馆,很低端的那种. uim指着墙上的价目表(太低级了没有菜单),说:“随便点”. 题目描述 不过u ...
- Ubuntu 16.04通过Magent搭建Memcached集群(转)
一.下载Magent 官网:https://code.google.com/archive/p/memagent/downloads 离线版本:(链接: https://pan.baidu.com/s ...
- GitHub现VMware虚拟机逃逸EXP,利用三月曝光的CVE-2017-4901漏洞
今年的Pwn2Own大赛后,VMware近期针对其ESXi.Wordstation和Fusion部分产品发布更新,修复在黑客大赛中揭露的一些高危漏洞.事实上在大赛开始之前VMware就紧急修复了一个编 ...
- 解决fragmentTransaction.replace不能全屏
今天遇到个问题,使用fragmentTransaction.replace替换后的内容不能全屏.. FragmentManager fragmentManager = getSupportFragme ...
- web面试集合
在JavaScript中,添加到页面上的事件处理程序数量将直接关系到页面的整体运行性能.导致这一问题的原因是多方面的.首先,每个函数都是对象,都会占用内存:内存中的对象越多,性能就越差.其次,必须事先 ...
- 通俗理解LDA主题模型
通俗理解LDA主题模型 0 前言 印象中,最開始听说"LDA"这个名词,是缘于rickjin在2013年3月写的一个LDA科普系列,叫LDA数学八卦,我当时一直想看来着,记得还打印 ...
- iOS NSMutableDictionary中UIImage的存储和读取
思路:将UIImage转换成NSData,然后插入到NSMutableDictionary中.读取时,用NSData读出来,然后再转换成UIImage -存储 UIImage *image = [se ...