目錄
- 一、CrawlSpider類介紹
- 二、案例:古詩文網全站數據爬取
- 2.1 爬蟲文件
- 2.2 item文件
- 2.3 管道文件
- 2.4 配置文件
- 2.5 輸出結果
一、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
對應的正則表達式提取響應對象中的鏈接
link = LinkExtractor(
# Items只能是一個正則表達式,會提取當前頁面中滿足該"正則表達式"的url
allow=r'Items/'
)
rules = (Rule(link, callback='parse_item', follow=True),)
:規則解析器
按照指定規則從鏈接提取器中提取到的鏈接中解析網頁數據
link:是一個LinkExtractor()對象,指定鏈接提取器
callback:回調函數,指定規則解析器(解析方法)解析數據
follow:是否將鏈接提取器繼續作用到鏈接提取器提取出的鏈接網頁中
import scrapy
# 導入相關的包
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule
class TextSpider(CrawlSpider):
name = 'text'
allowed_domains = ['www.xxx.com']
start_urls = ['http://www.xxx.com/']
# 鏈接提取器,從接受到的response對象中,根據item正則表達式提取頁面中的鏈接
link = LinkExtractor(allow=r'Items/')
link2 = LinkExtractor(allow=r'Items/')
# 規則解析器,根據callback將鏈接提取器提取到的鏈接進行數據解析
# follow為true,則表示將鏈接提取器繼續作用到鏈接提取器所提取到的鏈接頁面中
# 故:在我們提取多頁數據時,若第一頁對應的網頁中包含了第2,3,4,5頁的鏈接,
# 當跳轉到第5頁時,第5頁又包含了第6,7,8,9頁的鏈接,
# 令follow=True,就可以持續作用,從而提取到所有頁面的鏈接
rules = (Rule(link, callback='parse_item', follow=True),
Rule(link2,callback='parse_content',follow=False))
# 鏈接提取器link使用parse_item解析數據
def parse_item(self, response):
item = {}
yield item
# 鏈接提取器link2使用parse_content解析數據
def parse_content(self, response):
item = {}
yield item
1.2.2 使用
創建爬蟲文件:除了創建爬蟲文件不同外,創建項目和運行爬蟲使用的命令和基于Spider類使用的命令相同
scrapy genspider crawl -t spiderName www.xxx.com
二、案例:古詩文網全站數據爬取
爬取古詩文網首頁古詩的標題,以及每一首詩詳情頁古詩的標題和內容。
最后將從詳情頁提取到的古詩標題和內容進行持久化存儲
2.1 爬蟲文件
import scrapy
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule
from gushiPro.items import GushiproItem,ContentItem
class GushiSpider(CrawlSpider):
name = 'gushi'
#allowed_domains = ['www.xxx.com']
start_urls = ['https://www.gushiwen.org/']
# 鏈接提取器:只能使用正則表達式,提取當前頁面的滿足allow條件的鏈接
link = LinkExtractor(allow=r'/default_\d+\.aspx')
# 鏈接提取器,提取所有標題對應的詳情頁url
content_link = LinkExtractor(allow=r'cn/shiwenv_\w+\.aspx')
rules = (
# 規則解析器,需要解析所有的頁面,所有follow=True
Rule(link, callback='parse_item', follow=True),
# 不需要寫follow,因為我們只需要解析詳情頁中的數據,而不是詳情頁中的url
Rule(content_link, callback='content_item'),
)
# 解析當前頁面的標題
def parse_item(self, response):
p_list = response.xpath('//div[@class="sons"]/div[1]/p[1]')
for p in p_list:
title = p.xpath('./a//text()').extract_first()
item = GushiproItem()
item['title'] = title
yield item
# 解析詳情頁面的標題和內容
def content_item(self,response):
# //div[@id="sonsyuanwen"]/div[@class="cont"]/div[@class="contson"]
# 解析詳情頁面的內容
content = response.xpath('//div[@id="sonsyuanwen"]/div[@class="cont"]/div[@class="contson"]//text()').extract()
content = "".join(content)
# # 解析詳情頁面的標題
title = response.xpath('//div[@id="sonsyuanwen"]/div[@class="cont"]/h1/text()').extract_first()
# print("title:"+title+"\ncontent:"+content)
item = ContentItem()
item["content"] = content
item["title"] = title
# 將itme對象傳給管道
yield item
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 ItemAdapter
class 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數據爬取內容請搜索腳本之家以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持腳本之家!
您可能感興趣的文章:- python scrapy項目下spiders內多個爬蟲同時運行的實現
- Python爬蟲Scrapy框架CrawlSpider原理及使用案例
- Python Scrapy框架:通用爬蟲之CrawlSpider用法簡單示例
- Python爬蟲框架之Scrapy中Spider的用法