CrawlSpiders简介
转:https://www.cnblogs.com/ellisonzhang/p/11124516.html#4295547
一、CrawlSpiders类简介
通过下面的命令可以快速创建 CrawlSpider模板 的代码:
scrapy genspider -t crawl tencent tencent.com
上一个案例中,我们通过正则表达式,制作了新的url作为Request请求参数,现在我们可以换个花样...
class scrapy.spiders.CrawlSpider
它是Spider的派生类,Spider类的设计原则是只爬取start_url列表中的网页,而CrawlSpider类定义了一些规则(rule)来提供跟进link的方便的机制,从爬取的网页中获取link并继续爬取的工作更适合。
源码参考
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
|
class CrawlSpider(Spider): rules = () def __init__(self, *a, **kw): super(CrawlSpider, self).__init__(*a, **kw) self._compile_rules() #首先调用parse()来处理start_urls中返回的response对象 #parse()则将这些response对象传递给了_parse_response()函数处理,并设置回调函数为parse_start_url() #设置了跟进标志位True #parse将返回item和跟进了的Request对象 def parse(self, response): return self._parse_response(response, self.parse_start_url, cb_kwargs={}, follow=True) #处理start_url中返回的response,需要重写 def parse_start_url(self, response): return [] def process_results(self, response, results): return results #从response中抽取符合任一用户定义'规则'的链接,并构造成Resquest对象返回 def _requests_to_follow(self, response): if not isinstance(response, HtmlResponse): return seen = set() #抽取之内的所有链接,只要通过任意一个'规则',即表示合法 for n, rule in enumerate(self._rules): links = [l for l in rule.link_extractor.extract_links(response) if l not in seen] #使用用户指定的process_links处理每个连接 if links and rule.process_links: links = rule.process_links(links) #将链接加入seen集合,为每个链接生成Request对象,并设置回调函数为_repsonse_downloaded() for link in links: seen.add(link) #构造Request对象,并将Rule规则中定义的回调函数作为这个Request对象的回调函数 r = Request(url=link.url, callback=self._response_downloaded) r.meta.update(rule=n, link_text=link.text) #对每个Request调用process_request()函数。该函数默认为indentify,即不做任何处理,直接返回该Request. yield rule.process_request(r) #处理通过rule提取出的连接,并返回item以及request def _response_downloaded(self, response): rule = self._rules[response.meta['rule']] return self._parse_response(response, rule.callback, rule.cb_kwargs, rule.follow) #解析response对象,会用callback解析处理他,并返回request或Item对象 def _parse_response(self, response, callback, cb_kwargs, follow=True): #首先判断是否设置了回调函数。(该回调函数可能是rule中的解析函数,也可能是 parse_start_url函数) #如果设置了回调函数(parse_start_url()),那么首先用parse_start_url()处理response对象, #然后再交给process_results处理。返回cb_res的一个列表 if callback: #如果是parse调用的,则会解析成Request对象 #如果是rule callback,则会解析成Item cb_res = callback(response, **cb_kwargs) or () cb_res = self.process_results(response, cb_res) for requests_or_item in iterate_spider_output(cb_res): yield requests_or_item #如果需要跟进,那么使用定义的Rule规则提取并返回这些Request对象 if follow and self._follow_links: #返回每个Request对象 for request_or_item in self._requests_to_follow(response): yield request_or_item def _compile_rules(self): def get_method(method): if callable(method): return method elif isinstance(method, basestring): return getattr(self, method, None) self._rules = [copy.copy(r) for r in self.rules] for rule in self._rules: rule.callback = get_method(rule.callback) rule.process_links = get_method(rule.process_links) rule.process_request = get_method(rule.process_request) def set_crawler(self, crawler): super(CrawlSpider, self).set_crawler(crawler) self._follow_links = crawler.settings.getbool('CRAWLSPIDER_FOLLOW_LINKS', True) |
二、LinkExtractors
Link Extractors 的目的很简单: 提取链接。
每个LinkExtractor有唯一的公共方法是 extract_links(),它接收一个 Response 对象,并返回一个 scrapy.link.Link 对象。
Link Extractors要实例化一次,并且 extract_links 方法会根据不同的 response 调用多次提取链接。
主要参数
|
1
2
3
4
5
6
7
8
9
10
11
12
13
|
class scrapy.linkextractors.LinkExtractor( allow = (), # 满足括号中“正则表达式”的值会被提取,如果为空,则全部匹配 deny = (), # 与这个正则表达式(或正则表达式列表)不匹配的URL一定不提取 allow_domains = (), # 会被提取的链接的domains deny_domains = (), # 一定不会被提取链接的domains deny_extensions = None, restrict_xpaths = (), # 使用xpath表达式,和allow共同作用过滤链接(一般只用allow就行了) tags = ('a','area'), attrs = ('href'), canonicalize = True, unique = True, process_value = None) |
三、LinkExtractors
在rules中包含一个或多个Rule对象,每个Rule对爬取网站的动作定义了特定操作。如果多个rule匹配了相同的链接,则根据规则在本集合中被定义的顺序,第一个会被使用。
主要参数
|
1
2
3
4
5
6
7
8
|
class scrapy.spiders.Rule( link_extractor, callback = None, cb_kwargs = None, follow = None, process_links = None, process_request = None) |
link_extractor:是一个Link Extractor对象,用于定义需要提取的链接。callback: 从link_extractor中每获取到链接时,参数所指定的值作为回调函数,该回调函数接受一个response作为其第一个参数。注意:当编写爬虫规则时,避免使用parse作为回调函数。由于CrawlSpider使用parse方法来实现其逻辑,如果覆盖了 parse方法,crawl spider将会运行失败。
follow:是一个布尔(boolean)值,指定了根据该规则从response提取的链接是否需要跟进。 如果callback为None,follow 默认设置为True ,否则默认为False。process_links:指定该spider中哪个的函数将会被调用,从link_extractor中获取到链接列表时将会调用该函数。该方法主要用来过滤。process_request:指定该spider中哪个的函数将会被调用, 该规则提取到每个request时都会调用该函数。 (用来过滤request)
小Tips
|
1
|
由于CrawlSpider使用parse方法来实现其逻辑,如果覆盖了 parse方法,crawl spider将会运行失败。 |
四、Logging
Scrapy提供了log功能,可以通过 logging 模块使用。
可以修改配置文件settings.py,任意位置添加下面两行。
LOG_FILE = "TencentSpider.log"
LOG_LEVEL = "INFO"
Log levels
Scrapy提供5层logging级别:
CRITICAL - 严重错误(critical)
- ERROR - 一般错误(regular errors)
- WARNING - 警告信息(warning messages)
- INFO - 一般信息(informational messages)
- DEBUG - 调试信息(debugging messages)
logging设置
通过在setting.py中进行以下设置可以被用来配置logging:
LOG_ENABLED默认: True,启用loggingLOG_ENCODING默认: 'utf-8',logging使用的编码LOG_FILE默认: None,在当前目录里创建logging输出文件的文件名LOG_LEVEL默认: 'DEBUG',log的最低级别LOG_STDOUT默认: False 如果为 True,进程所有的标准输出(及错误)将会被重定向到log中。例如,执行 print "hello" ,其将会在Scrapy log中显示。
示例1、使用CrawlSpider爬取腾讯招聘网站
爬虫模块
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
|
# -*- coding: utf-8 -*-import scrapyfrom scrapy.linkextractors import LinkExtractor # 导入链接规则匹配类,用来提取符合规则的连接from scrapy.spiders import CrawlSpider, Rule # 导入CrawlSpider类和Rulefrom day_31.TencentCrawlSpider.TencentCrawlSpider.items import TencentcrawlspiderItemclass TencentSpider(CrawlSpider): name = 'tencent' allowed_domains = ['tencent.com'] start_urls = ['http://hr.tencent.com/position.php?&start=0'] rules = ( Rule(LinkExtractor(allow=r'position\.php\?&start=\d+#a'), callback='parse_item', follow=True), # Response里链接的提取规则,返回的符合匹配规则的链接匹配对象的列表 # 获取这个列表里的链接,依次发送请求,并且继续跟进,调用指定回调函数处理 # 前面加r表示将正则表达式编译成一个规则的对象 ) # 指定的回调函数 def parse_item(self, response): for i in response.xpath('//tr[@class="even"] | //tr[@class="odd"]'): item = TencentcrawlspiderItem() item['name'] = i.xpath(".//a/text()").extract()[0] item['link'] = i.xpath(".//a/@href").extract()[0] item['type'] = i.xpath("./td[2]/text()").extract()[0] item['number'] = i.xpath(".//td[3]/text()").extract()[0] item['place'] = i.xpath(".//td[4]/text()").extract()[0] item['rtime'] = i.xpath(".//td[5]/text()").extract()[0] yield item |
管道模块
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
# -*- coding: utf-8 -*-# Define your item pipelines here## Don't forget to add your pipeline to the ITEM_PIPELINES setting# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.htmlimport jsonclass TencentcrawlspiderPipeline(object): def __init__(self): self.file = open('tencent-job.json','wb') def process_item(self, item, spider): text = json.dumps(dict(item),ensure_ascii=False)+'\n' self.file.write(text.encode('utf-8')) return item def close_spider(self, spider): self.file.close() |
小Tips
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
1、python 爬虫爬取内容时, \xa0 、 \u3000 的含义\xa0 是不间断空白符 我们通常所用的空格是 \x20 ,是在标准ASCII可见字符 0x20~0x7e 范围内。而 \xa0 属于 latin1 (ISO/IEC_8859-1)中的扩展字符集字符,代表空白符nbsp(non-breaking space)。latin1 字符集向下兼容 ASCII ( 0x20~0x7e )。通常我们见到的字符多数是 latin1 的,比如在 MySQL 数据库中。\u3000 是全角的空白符根据Unicode编码标准及其基本多语言面的定义, \u3000 属于CJK字符的CJK标点符号区块内,是空白字符之一。它的名字是 Ideographic Space ,有人译作表意字空格、象形字空格等。顾名思义,就是全角的 CJK 空格。它跟 nbsp 不一样,是可以被换行间断的。常用于制造缩进, wiki 还说用于抬头,但没见过。2、response.url # 获取当前页面url3、在allow里面的正则匹配,有特殊字符('.','?')要加转义字符'\'page_lx = LinkExtractor(allow=('position\.php\?&start=\d+'))4、字符串去空格 str.strip() |
示例二:爬取网页里面的信息(东莞)
爬虫模块
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
|
# -*- coding: utf-8 -*-import scrapyfrom scrapy.linkextractors import LinkExtractorfrom scrapy.spiders import CrawlSpider, Rulefrom newdongguan.items import NewdongguanItemclass DongdongSpider(CrawlSpider): name = 'dongdong' allowed_domains = ['wz.sun0769.com'] start_urls = ['http://wz.sun0769.com/index.php/question/questionType?type=4&page='] # 每一页的匹配规则 pagelink = LinkExtractor(allow=("type=4")) # 每一页里的每个帖子的匹配规则 contentlink = LinkExtractor(allow=(r"/html/question/\d+/\d+.shtml")) rules = ( Rule(pagelink), Rule(contentlink, callback = "parse_item",follow=False) ) def parse_item(self, response): item = NewdongguanItem() # 标题 item['title'] = response.xpath('//div[contains(@class, "pagecenter p3")]//strong/text()').extract()[0] # 编号 item['number'] = item['title'].split(' ')[-1].split(":")[-1] # 内容,先使用有图片情况下的匹配规则,如果有内容,返回所有内容的列表集合 content = response.xpath('//div[@class="contentext"]/text()').extract() # 如果没有内容,则返回空列表,则使用无图片情况下的匹配规则 if len(content) == 0: content = response.xpath('//div[@class="c1 text14_2"]/text()').extract() item['content'] = "".join(content).strip() else: item['content'] = "".join(content).strip() # 链接 item['url'] = response.url yield item |
管道模块
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
# -*- coding: utf-8 -*-# Define your item pipelines here## Don't forget to add your pipeline to the ITEM_PIPELINES setting# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.htmlimport jsonclass DongguancrawlspiderPipeline(object): def __init__(self): self.file = open('dongguan.json','wb') def process_item(self, item, spider): text = json.dumps(dict(item),ensure_ascii=False)+'\n' self.file.write(text.encode('utf-8')) return item def close_spider(self,spider): self.file.close() |
1、提取出来的链接可能被篡改,所以我们可以通过process_link来修改url(一般不会遇到)
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
|
import scrapyfrom scrapy.linkextractors import LinkExtractorfrom scrapy.spiders import CrawlSpider, Rulefrom newdongguan.items import NewdongguanItemclass DongdongSpider(CrawlSpider): name = 'dongdong' allowed_domains = ['wz.sun0769.com'] start_urls = ['http://wz.sun0769.com/index.php/question/questionType?type=4&page='] # 每一页的匹配规则 pagelink = LinkExtractor(allow=("type=4")) # 每一页里的每个帖子的匹配规则 contentlink = LinkExtractor(allow=(r"/html/question/\d+/\d+.shtml")) rules = ( # 本案例的url被web服务器篡改,需要调用process_links来处理提取出来的url Rule(pagelink, process_links = "deal_links"), Rule(contentlink, callback = "parse_item") ) # links 是当前response里提取出来的链接列表 def deal_links(self, links): for each in links: each.url = each.url.replace("?","&").replace("Type&","Type?") return links def parse_item(self, response): ... |
2、修改成spider类
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
|
# -*- coding: utf-8 -*-import scrapyfrom newdongguan.items import NewdongguanItemclass DongdongSpider(scrapy.Spider): name = 'xixi' allowed_domains = ['wz.sun0769.com'] url = 'http://wz.sun0769.com/index.php/question/questionType?type=4&page=' offset = 0 start_urls = [url + str(offset)] def parse(self, response): # 每一页里的所有帖子的链接集合 links = response.xpath('//div[@class="greyframe"]/table//td/a[@class="news14"]/@href').extract() # 迭代取出集合里的链接 for link in links: # 提取列表里每个帖子的链接,发送请求放到请求队列里,并调用self.parse_item来处理 yield scrapy.Request(link, callback = self.parse_item) # 页面终止条件成立前,会一直自增offset的值,并发送新的页面请求,调用parse方法处理 if self.offset <= 71160: self.offset += 30 # 发送请求放到请求队列里,调用self.parse处理response yield scrapy.Request(self.url + str(self.offset), callback = self.parse) # 处理每个帖子的response内容 def parse_item(self, response): item = NewdongguanItem() # 标题 item['title'] = response.xpath('//div[contains(@class, "pagecenter p3")]//strong/text()').extract()[0] # 编号 item['number'] = item['title'].split(' ')[-1].split(":")[-1] # 内容,先使用有图片情况下的匹配规则,如果有内容,返回所有内容的列表集合 content = response.xpath('//div[@class="contentext"]/text()').extract() # 如果没有内容,则返回空列表,则使用无图片情况下的匹配规则 if len(content) == 0: content = response.xpath('//div[@class="c1 text14_2"]/text()').extract() item['content'] = "".join(content).strip() else: item['content'] = "".join(content).strip() # 链接 item['url'] = response.url # 交给管道 yield item |
小Tips:
|
1
2
3
4
5
6
7
8
9
10
|
list = [a,b,c]string = "123".join(list)print(string)>> a 123b 123cstring.replace("\xa0","") # 将空格换成空string.strip() # 去首尾的空格string.lstrip() # 去左边(前面)的空格string.rstrip() # 去右边(后面)的空格 |
CrawlSpiders简介的更多相关文章
- ASP.NET Core 1.1 简介
ASP.NET Core 1.1 于2016年11月16日发布.这个版本包括许多伟大的新功能以及许多错误修复和一般的增强.这个版本包含了多个新的中间件组件.针对Windows的WebListener服 ...
- MVVM模式和在WPF中的实现(一)MVVM模式简介
MVVM模式解析和在WPF中的实现(一) MVVM模式简介 系列目录: MVVM模式解析和在WPF中的实现(一)MVVM模式简介 MVVM模式解析和在WPF中的实现(二)数据绑定 MVVM模式解析和在 ...
- Cassandra简介
在前面的一篇文章<图形数据库Neo4J简介>中,我们介绍了一种非常流行的图形数据库Neo4J的使用方法.而在本文中,我们将对另外一种类型的NoSQL数据库——Cassandra进行简单地介 ...
- REST简介
一说到REST,我想大家的第一反应就是“啊,就是那种前后台通信方式.”但是在要求详细讲述它所提出的各个约束,以及如何开始搭建REST服务时,却很少有人能够清晰地说出它到底是什么,需要遵守什么样的准则. ...
- Microservice架构模式简介
在2014年,Sam Newman,Martin Fowler在ThoughtWorks的一位同事,出版了一本新书<Building Microservices>.该书描述了如何按照Mic ...
- const,static,extern 简介
const,static,extern 简介 一.const与宏的区别: const简介:之前常用的字符串常量,一般是抽成宏,但是苹果不推荐我们抽成宏,推荐我们使用const常量. 执行时刻:宏是预编 ...
- HTTPS简介
一.简单总结 1.HTTPS概念总结 HTTPS 就是对HTTP进行了TLS或SSL加密. 应用层的HTTP协议通过传输层的TCP协议来传输,HTTPS 在 HTTP和 TCP中间加了一层TLS/SS ...
- 【Machine Learning】机器学习及其基础概念简介
机器学习及其基础概念简介 作者:白宁超 2016年12月23日21:24:51 摘要:随着机器学习和深度学习的热潮,各种图书层出不穷.然而多数是基础理论知识介绍,缺乏实现的深入理解.本系列文章是作者结 ...
- Cesium简介以及离线部署运行
Cesium简介 cesium是国外一个基于JavaScript编写的使用WebGL的地图引擎,一款开源3DGIS的js库.cesium支持3D,2D,2.5D形式的地图展示,可以自行绘制图形,高亮区 ...
随机推荐
- 安装php5.4 mv9 +apache2.2+mysql5.5问题好多。
1 网站目录的设置,网站 默认文件的加载. 2 php.ini文件的加载问题.
- [LC] 211. Add and Search Word - Data structure design
Design a data structure that supports the following two operations: void addWord(word) bool search(w ...
- css - 原生变量及使用函数 var()
零.序言 前两天在逛 blog 的时候看见一些内联样式新奇的写法时很纳闷,虽然说不上多么熟练,但是从来没见过 --color: brown 这样的写法,百度一番之后仍然没啥头绪,今天偶然看到一篇文章 ...
- windows 不能在本地计算机启动apache2。有关更多信息,查阅系统事件日志。如果这是非Microsoft服务,请与服务厂商联系,并参考特定服务错误代码1
今天使用apache的时候又无法启动了,之前也遇到过,这次重点说这一次的情况,其他情况可以查看博主apache相关的其他博文:网上关于apache服务端的设置的很多,但是都不适合我的情况: 一般使用a ...
- 三步教你实现MyEclipse的debug远程调试
MyEclipse远程调试程序是个神奇的东西,有时一个项目本地运行没问题可放到服务器上,同样的条件就是结果不一样:有时服务器上工程出点问题需要远程调测.于是就灰常想看一下程序在远程运行时候的状态,希望 ...
- IOC初始化销毁的2种实现方式
IOC初始化销毁的2种实现方式 1.bean内调用init-method 和destroy-method 2.通过注解实现@PostConstruct 和@PreDestroy ----------- ...
- pycharm中无法导入pip安装的包
https://blog.csdn.net/mdxiaohu/article/details/82430060 2020.1.20 练习通过python操作数据库的时候需要导入一个包,因为看代码写的是 ...
- 吴裕雄--天生自然HTML学习笔记:HTML 图像
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title> ...
- 学习和使用 Styled Layer Descriptor SLD样式文件
1. SLD 文件大致作用,可以浏览下示意图: 点要素的符号化:http://docs.geoserver.org/stable/en/user/styling/sld-cookbook/points ...
- FastJson的学习之JSON互相转Map集合,List集合,JavaBean
https://blog.csdn.net/weixin_36910300/article/details/79182120 创建两个实体类 一个是部门类,一个是部门员工类 部门员工类 public ...