以下是我的學習筆記,以及總結,如有錯誤之處請不吝賜教。
本文主要介紹Scrapy框架及相應應用代碼。
Scrapy基礎:
是一個用於爬行web站點和提取結構化數據的應用程序框架,可用於各種有用的應用程序,如數據挖掘、信息處理或歷史檔案,官網;
scrapy結構包括:引擎(Scrapy Engine) 、調度器(Scheduler) 、下載器(Downloader) 、蜘蛛(Spiders) 、項目管道(Item Pipeline) 、下載器中間件(Downloader Middlewares) 、蜘蛛中間件(Spider Middlewares)、調度中間件(Scheduler Middlewares) ,如下圖:
Scrapy工作方式:箭頭表示的就是數據流向:
- 從初始URL開始,Scheduler會將其交給Downloader進行下載
- 下載之後會交給Spider進行分析
- Spider分析出來的結果有兩種 :①一種是需要進一步抓取的鏈接,如 “下一頁”的鏈接,它們會被傳回Scheduler; ②一種是需要進一步抓取的鏈接,如 “下一頁”的鏈接,它們會被傳回Scheduler;
- 在數據流動的通道里還可以安裝各種中間件,進行必要的處理。
Scrapy應用:
- Spider運行:scrapy runspider spider.py -o xxx.json,推薦json、xml、csv格式,方便導入數據庫。
- Scrapy項目創建:scrapy startproject xxx
- Scrapy shell:調試xpath網址
- Scrapy spider 爬取流程:①先初始化請求URL列表,並指定下載後處理response的回調函數;②在parse回調中解析response並返回字典,Item對象,Request對象或它們的迭代對象;③在回調函數裏面,使用選擇器解析頁面內容,並生成解析後的結果Item;④最後返回的這些Item通常會被持久化到數據庫中(使用Item Pipeline)或者使用Feed exports將其保存到文件中。
import scrapy class QQNewsSpider(scrapy.Spider): name = 'qqnews' start_urls = ['http://news.qq.com/society_index.shtml'] def parse(self, response): for href in response.xpath('//*[@id="news"]/div/div/div/div/em/a/@href'): full_url = response.urljoin(href.extract()) yield scrapy.Request(full_url, callback=self.parse_question) def parse_question(self, response): print response.xpath('//div[@class="qq_article"]/div/h1/text()').extract_first() print response.xpath('//span[@class="a_time"]/text()').extract_first() print response.xpath('//span[@class="a_catalog"]/a/text()').extract_first() print "\n".join(response.xpath('//div[@id="Cnt-Main-Article-QQ"]/p[@class="text"]/text()').extract()) print "" yield { 'title': response.xpath('//div[@class="qq_article"]/div/h1/text()').extract_first(), 'content': "\n".join(response.xpath('//div[@id="Cnt-Main-Article-QQ"]/p[@class="text"]/text()').extract()), 'time': response.xpath('//span[@class="a_time"]/text()').extract_first(), 'cate': response.xpath('//span[@class="a_catalog"]/a/text()').extract_first(), }
-
Scrapy spider爬取方式:
-
爬取1頁內容:
import scrapy class eduSpider(scrapy.Spider): name = "edu" start_urls = [ 'https://www.edu.com/category/index', ] def parse(self, response): for edu_class in response.xpath('//div[@class="course_info_box"]'): print(edu_class.xpath('a/h4/text()').extract_first()) print(edu_class.xpath('a/p[@class="course-info-tip"][1]/text()').extract_first()) print(edu_class.xpath('a/p[@class="course-info-tip"][2]/text()').extract_first()) print( response.urljoin(edu_class.xpath('a/img[1]/@src').extract_first())) print( "\n") yield { 'title':edu_class.xpath('a/h4/text()').extract_first(), 'desc': edu_class.xpath('a/p[@class="course-info-tip"][1]/text()').extract_first(), 'time': edu_class.xpath('a/p[@class="course-info-tip"][2]/text()').extract_first(), 'img_url': response.urljoin(edu_class.xpath('a/img[1]/@src').extract_first()) }
-
按照給定列表爬取多頁:
import scrapy class CnBlogSpider(scrapy.Spider): name = "cnblogs" allowed_domains = ["cnblogs.com"] start_urls = [ 'http://www.cnblogs.com/pick/#p%s' % p for p in xrange(1, 11) ] def parse(self, response): for article in response.xpath('//div[@class="post_item"]'): print article.xpath('div[@class="post_item_body"]/h3/a/text()').extract_first().strip() print response.urljoin(article.xpath('div[@class="post_item_body"]/h3/a/@href').extract_first()).strip() print article.xpath('div[@class="post_item_body"]/p/text()').extract_first().strip() print article.xpath('div[@class="post_item_body"]/div[@class="post_item_foot"]/a/text()').extract_first().strip() print response.urljoin(article.xpath('div[@class="post_item_body"]/div/a/@href').extract_first()).strip() print article.xpath('div[@class="post_item_body"]/div[@class="post_item_foot"]/span[@class="article_comment"]/a/text()').extract_first().strip() print article.xpath('div[@class="post_item_body"]/div[@class="post_item_foot"]/span[@class="article_view"]/a/text()').extract_first().strip() print "" yield { 'title': article.xpath('div[@class="post_item_body"]/h3/a/text()').extract_first().strip(), 'link': response.urljoin(article.xpath('div[@class="post_item_body"]/h3/a/@href').extract_first()).strip(), 'summary': article.xpath('div[@class="post_item_body"]/p/text()').extract_first().strip(), 'author': article.xpath('div[@class="post_item_body"]/div[@class="post_item_foot"]/a/text()').extract_first().strip(), 'author_link': response.urljoin(article.xpath('div[@class="post_item_body"]/div/a/@href').extract_first()).strip(), 'comment': article.xpath('div[@class="post_item_body"]/div[@class="post_item_foot"]/span[@class="article_comment"]/a/text()').extract_first().strip(), 'view': article.xpath('div[@class="post_item_body"]/div[@class="post_item_foot"]/span[@class="article_view"]/a/text()').extract_first().strip(), }
-
“下一頁”類型:
import scrapy class QuotesSpider(scrapy.Spider): name = "quotes" start_urls = [ 'http://quotes.toscrape.com/tag/humor/', ] def parse(self, response): for quote in response.xpath('//div[@class="quote"]'): yield { 'text': quote.xpath('span[@class="text"]/text()').extract_first(), 'author': quote.xpath('span/small[@class="author"]/text()').extract_first(), } next_page = response.xpath('//li[@class="next"]/@herf').extract_first() if next_page is not None: next_page = response.urljoin(next_page) yield scrapy.Request(next_page, callback=self.parse)
-
按照鏈接進行爬取:
import scrapy class StackOverflowSpider(scrapy.Spider): name = 'stackoverflow' start_urls = ['http://stackoverflow.com/questions?sort=votes'] def parse(self, response): for href in response.xpath('//*[@class="question-summary"]/div[2]/h3/a/@href'): full_url = response.urljoin(href.extract()) yield scrapy.Request(full_url, callback=self.parse_question) def parse_question(self, response): yield { 'title': response.xpath('//*[@id="question-header"]/h1/a/text()').extract(), 'votes': response.xpath('//span[@itemprop="upvoteCount"]/text()').extract_first(), 'body': response.xpath('//*[@id="question"]/table/tbody/tr[1]/td[2]/div/div[1]/text()').extract(), 'tags': ",".join(response.xpath('//div[@class="post-taglist"]/a/text()').extract()), 'link': response.url, }
-
不同類型spider:
-
CrawlSpider :鏈接爬取蜘蛛 ,屬性rules:Rule對象列表,定義規則:
- XMLFeedSpider :XML訂閱蜘蛛,通過某個指定的節點來遍歷 :
- CSVFeedSpider :類似XML訂閱蜘蛛,逐行迭代,調用parse_row()解析:
- Scrapy組件Item:①保存數據的地方; ②Item Loader可方便填充
-
Scrapy組件Item Pipeline :
-
當一個item被蜘蛛爬取到之後會被髮送給Item Pipeline,然後多個組件按照順序處理這個item;
-
Item Pipeline常用場景:①清理HTML數據 ;②驗證被抓取的數據(檢查item是否包含某些字段) ;③重複性檢查(然後丟棄) ;④將抓取的數據存儲到數據庫中
-
定義一個Python類,實現方法process_item(self, item, spider)即可,返回一個字典或Item,或者拋出DropItem異常丟棄這個Item。
-
經常會實現以下的方法:①open_spider(self, spider) 蜘蛛打開的時執行;②close_spider(self, spider) 蜘蛛關閉時執行 ;f③rom_crawler(cls, crawler) 可訪問核心組件比如配置和信號,並註冊鉤子函數到Scrapy中
-
具體案例代碼:
To be continue......