CrawlSpider
1.1 CrawlSpider简介:
**CrawlSpider: **CrawlSpider继承自Spider,是scrapy的一个模板。只不过是在之前的基础之上增加了新的功能,可以定义爬取的url的规则,以后scrapy碰到满足条件的url都进行爬取,而不用手动的yield Request。
1.2 CrawlSpider的生成:
之前创建爬虫的方式是通过
scrapy genspider [爬虫名字] [域名]
的方式创建的。如果想要创建CrawlSpider爬虫,那么cd到scrapy的项目根目录下后,应该通过以下命令创建:
scrapy genspider -t crawl [爬虫名字] [域名]
1.3 CrawlSpider解析:
Rule规则类:
定义爬虫的规则类。以下对这个类做一个简单的介绍:
例如:
rules = (
Rule(LinkExtractor(allow=r'.+mod=list&catid=2&page=\d'), follow=True),
Rule(LinkExtractor(allow=r'.+article-.+\.html'), callback='parse_detail', follow=False),
)
class scrapy.spiders.Rule(link_extractor, callback = None, cb_kwargs = None, follow = None, process_links = None, process_request = None)
主要参数讲解:
link_extractor:一个LinkExtractor对象,用于定义爬取规则。
callback 回调:满足这个规则的网址,应该要执行其中的某些函数。因为CrawlSpider使用了parse作为替代函数,因此不要覆盖parse作为替代函数自己的替代函数。
回调Ture大概意思是爬取一个详情页之后,返回数据给本机进行解析(判断该页面是否有获取的价值),callback='parse_detail',parse_detail为你要返回位置的函数名。
follow按照:指定根据该规则从response中提取的链接是否需要跟进。Ture大概意思是在爬取任何一页时,达到某一页时(比如第10页)继续跟进,解析其他详情页。换句话说,当你在爬取一个规则(link_extractor)的URL时,当这个URL发现相同规则的URL,是否跟进。当这个网页需要下载解析的时候一般时False,避免提取出重复的URL。或者说存在callback一般不存在follow=1。
process_links:从link_extractor中获取到链接后会传递给这个函数,用作过滤不需要爬取的链接。
1.4 CrawlSpider实例:
第一步:settings.py文件进行设置
ROBOTSTXT_OBEY = False #注释:
DOWNLOAD_DELAY = 1 #注释:限制下载速度,避免被限制访问。
DEFAULT_REQUEST_HEADERS = {
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Accept-Language': 'en',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36'
}
#注释:请求头设置。
ITEM_PIPELINES = {
'wxapp.pipelines.WxappPipeline': 300,
}
#注释:开启Pipeline,也就是说运行运行pipelines.py,优先级设置为300
第二步:Item.py文件编写
import scrapy
class WxappItem(scrapy.Item):
# define the fields for your item here like:
title = scrapy.Field()
author = scrapy.Field()
content = scrapy.Field()
第三步:scrapy爬虫文件编写
# -*- coding: utf-8 -*-
import scrapy
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule
from wx.wxapp.wxapp.items import WxappItem
class WxappSpiderSpider(CrawlSpider):
name = 'wxapp_spider'
allowed_domains = ['wxapp-union.com']
start_urls = ['http://www.wxapp-union.com/portal.php?mod=list&catid=2&page=1']
rules = (
Rule(LinkExtractor(allow=r'.+mod=list&catid=2&page=\d'), follow=True),
Rule(LinkExtractor(allow=r'.+article-.+\.html'), callback='parse_detail', follow=False),
)
def parse_detail(self, response):
title = response.xpath("//div[@class='cl']/h1[@class='ph']/text()").get()
author = response.xpath("//p[@class='authors']/a/text()").get()
article_content = response.xpath("//td[@id='article_content']//text()").getall()
content = "".join(article_content).strip()
print('title:%s\n author:%s \n content:%s' % (title,author,content))
print('='*40)
item = WxappItem(title=title,author=author,content=content)
print('=' * 40)
print('=' * 40)
yield item
第五步:pipelines.py文件编写,将数据储存到json
# -*- 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
from scrapy.exporters import JsonLinesItemExporter
class WxappPipeline(object):
def __init__(self):
self.fp = open("wxjc.json",'wb')
self.exporter = JsonLinesItemExporter(self.fp,ensure_ascii=False,encoding='utf-8')
def open_spider(self,spider):
print('爬虫开始了……')
def process_item(self, item, spider):
self.exporter.export_item(item)
return item
def close_spider(self,spider):
self.fp.close()
print('爬虫结束了……')
pass
运行效果: