一、CrawlSpider类介绍
1.1 引入
使用scrapy框架进行全站数据爬取可以基于Spider类,也可以使用接下来用到的CrawlSpider类。基于Spider类的全站数据爬取之前举过栗子,感兴趣的可以康康
scrapy基于CrawlSpider类的全站数据爬取
1.2 介绍和使用
1.2.1 介绍
CrawlSpider是Spider的一个子类,因此CrawlSpider除了继承Spider的特性和功能外,还有自己特有的功能,主要用到的是 LinkExtractor()和rules = (Rule(LinkExtractor(allow=r'Items/'), callback='parse_item', follow=True),)
LinkExtractor():链接提取器
LinkExtractor()接受response对象,并根据allow对应的正则表达式提取响应对象中的链接
rules = (Rule(link, callback='parse_item', follow=True),):规则解析器
按照指定规则从链接提取器中提取到的链接中解析网页数据
link:是一个LinkExtractor()对象,指定链接提取器
callback:回调函数,指定规则解析器(解析方法)解析数据
follow:是否将链接提取器继续作用到链接提取器提取出的链接网页中
2.2 item文件
import scrapy# 不同的item类是独立的,他们可以创建不同的item对象class GushiproItem(scrapy.Item): # define the fields for your item here like: # name = scrapy.Field() title = scrapy.Field()class ContentItem(scrapy.Item): title = scrapy.Field() content = scrapy.Field()2.3 管道文件
from itemadapter import ItemAdapterclass GushiproPipeline: def __init__(self): self.fp = None def open_spider(self,spider): self.fp = open("gushi.txt",'w',encoding='utf-8') print("开始爬虫") def process_item(self, item, spider): # 从详情页获取标题和内容,所以需要判断爬虫文件中传来的item是什么类的item # item.__class__.__name__判断属于什么类型的item if item.__class__.__name__ == "ContentItem": content = "《"+item['title']+"》",item['content'] content = "".join(content) print(content) self.fp.write(content) return item def close_spider(self,spider): self.fp.close() print("结束爬虫")2.4 配置文件
2.5 输出结果
到此这篇关于python爬虫scrapy基于CrawlSpider类的全站数据爬取示例解析的文章就介绍到这了,更多相关python爬虫scrapy数据爬取内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!