创建CrawlSpider爬虫
上篇博客中,写的创建爬虫的方式是通过 scrapy genspider [爬虫名字] [域名]
创建的。如果想要创建 CrawlSpider
爬虫,应该通过如下命令进行
scrapy genspider -t crawl [爬虫名字] [域名]
-t
: 是选择模板生成代码,因为是要编写CrawlSpider
爬虫所以选择crawl
模板
输入 scrapy genspider -t crawl qsbk_two www.qiushibaike.com
后生成的python代码如下
# -*- coding: utf-8 -*-
import scrapy
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule
class QsbkTwoSpider(CrawlSpider):
name = 'qsbk_two'
allowed_domains = ['www.qiushibaike.com']
start_urls = ['http://www.qiushibaike.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
查看代码可以发现除了编写爬虫需要继承的 CrawlSpider
类外,还多了两个新的依赖 LinkExtractor
和 Rule
LinkExtractor链接提取器
使用LinkExtractors
可以不用自己提取想要的url,然后发送请求。这些工作都可以交给LinkExtractors
,他会在所有爬的页面中找到满足规则的url,实现自动的爬取。以下对LinkExtractors
类做一个简单的介绍:
LinkExtractors
类的构造方法如下:
def __init__(self,
allow=(),
deny=(),
allow_domains=(),
deny_domains=(),
restrict_xpaths=(),
tags=('a', 'area'),
attrs=('href',),
canonicalize=False,
unique=True,
process_value=None,
deny_extensions=None,
restrict_css=(),
strip=True):
# 代码省略
pass
主要参数讲解
参数名 | 说明 |
---|---|
allow | 允许的url。所有满足这个正则表达式的url都会被提取 |
deny | 禁止的url。所有满足这个正则表达式的url都不会被提取 |
allow_domains | 允许的域名。只有在这个里面指定的域名的url才会被提取 |
deny_domains | 禁止的域名。所有在这个里面指定的域名的url都不会被提取 |
restrict_xpaths | 严格的xpath。和allow共同过滤链接 |
Rule规则类
定义爬虫的规则类。以下对这个类做一个简单的介绍:
构造函数如下:
def __init__(self,
link_extractor,
callback=None,
cb_kwargs=None,
follow=None,
process_links=None,
process_request=identity):
# 代码省略
pass
主要参数讲解
参数名 | 说明 |
---|---|
link_extractor | 一个LinkExtractor对象,用于定义爬取规则 |
callback | 满足这个规则的url,应该要执行哪个回调函数。因为CrawlSpider使用了parse作为回调函数,因此不要覆盖parse作为回调函数自己的回调函数 |
follow | 指定根据该规则从response中提取的链接是否需要跟进 |
process_links | 从link_extractor中获取到链接后会传递给这个函数,用来过滤不需要爬取的链接 |
糗事百科CrawlSpider案例
依照上篇博客的代码在spiders
包中新添加一个 CrawlSpider
爬虫类
代码如下
# -*- coding: utf-8 -*-
import scrapy
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule
from qsbk.items import QsbkItem
import time
class QsbkTwoSpider(CrawlSpider):
name = 'qsbk_two'
allowed_domains = ['www.qiushibaike.com']
start_urls = ['https://www.qiushibaike.com/text/']
link_extractor = LinkExtractor(allow='/text/page/\d+/')
rules = (
Rule(link_extractor=link_extractor, callback='parse_item', follow=True),
)
def parse_item(self, response):
outerbox = response.xpath("//div[@id='content-left']/div")
items = []
for box in outerbox:
detail_url = str(box.xpath("a[1]/@href").get()).strip()
author = str(box.xpath("div[@class='author clearfix']/a/h2/text()").get()).strip()
content = str(box.xpath("a/div[@class='content']/span/text()").get()).strip()
item = QsbkItem()
item['detail_url'] = detail_url
item['author'] = author
item['content'] = content
cmt_box = box.xpath("a[@class='indexGodCmt']")
if len(cmt_box) > 0:
cmt_name = str(cmt_box[0].xpath("div/span[@class='cmt-name']/text()").get()).strip()[0:-1]
item['cmt_name'] = cmt_name
cmt_content = str(cmt_box[0].xpath("div/div/text()").get()).strip()
item['cmt_content'] = cmt_content
items.append(item)
return items
parse_item
方法中的代码和之前的爬虫代码相差不大,只是多了爬取审评字段,这里直接看代码不在过多描述,主要说下 link_extractor
和 rules
-
link_extractor
: 经检查发现每页的链接是/text/page/[数字]/
这种形式,所以我们可以通过编写一个简单的正则对链接进行过滤/text/page/\d+/
。链接如果前边没域名CrawlSpider
会自动将当前网站的域名拼接上去。 -
rules
:link_extractor
参数传入了上边创建好的LinkExtractor
对象,callback
参数指定了创建的parse_item
为回调方法,follow
参数设置为True
指定如果提取到链接则请求新的链接继续执行
然后修改 start.py
中的启动命令为 scrapy crawl qsbk_two
来启动新创建的这个爬虫,然后可以看到CrawlSpider
会自动爬取每页的数据,以爬取过的链接会自动过滤不会进行重复请求