Python Scrapy框架:通用爬蟲之CrawlSpider用法簡單示例
阿新 • • 發佈:2020-04-13
本文例項講述了Python Scrapy框架:通用爬蟲之CrawlSpider用法。分享給大家供大家參考,具體如下:
步驟01: 建立爬蟲專案
scrapy startproject quotes
步驟02: 建立爬蟲模版
scrapy genspider -t quotes quotes.toscrape.com
步驟03: 配置爬蟲檔案quotes.py
import scrapy from scrapy.spiders import CrawlSpider,Rule from scrapy.linkextractors import LinkExtractor class Quotes(CrawlSpider): # 爬蟲名稱 name = "get_quotes" allow_domain = ['quotes.toscrape.com'] start_urls = ['http://quotes.toscrape.com/'] # 設定規則 rules = ( # 對於quotes內容頁URL,呼叫parse_quotes處理, # 並以此規則跟進獲取的連結 Rule(LinkExtractor(allow=r'/page/\d+'),callback='parse_quotes',follow=True),# 對於author內容頁URL,呼叫parse_author處理,提取資料 Rule(LinkExtractor(allow=r'/author/\w+'),callback='parse_author') ) # 提取內容頁資料方法 def parse_quotes(self,response): for quote in response.css(".quote"): yield {'content': quote.css('.text::text').extract_first(),'author': quote.css('.author::text').extract_first(),'tags': quote.css('.tag::text').extract() } # 獲取作者資料方法 def parse_author(self,response): name = response.css('.author-title::text').extract_first() author_born_date = response.css('.author-born-date::text').extract_first() author_bron_location = response.css('.author-born-location::text').extract_first() author_description = response.css('.author-description::text').extract_first() return ({'name': name,'author_bron_date': author_born_date,'author_bron_location': author_bron_location,'author_description': author_description })
步驟04: 執行爬蟲
scrapy crawl quotes
更多相關內容可檢視本站專題:《Python Socket程式設計技巧總結》、《Python正則表示式用法總結》、《Python資料結構與演算法教程》、《Python函式使用技巧總結》、《Python字串操作技巧彙總》、《Python入門與進階經典教程》及《Python檔案與目錄操作技巧彙總》
希望本文所述對大家基於Scrapy框架的Python程式設計有所幫助。