Scrapy之爬取結(jié)果導(dǎo)出為Excel的實現(xiàn)過程
引言
基于Scrapy來爬取數(shù)據(jù)只是手段,這些爬取的結(jié)果需要按照一定的方式導(dǎo)出或者存儲到數(shù)據(jù)庫中,
excel是在日常工作中使用最為廣泛的工具之一,本文介紹如何來講爬取結(jié)果存儲excel文件。
環(huán)境介紹
Python 3.6.1 Scrapy 1.5.0
定義Domain對象
定義爬取數(shù)據(jù)對象的實體類:
import scrapy class EnrolldataItem(scrapy.Item): ? ? schoolName = scrapy.Field() ? ? currentBatch = scrapy.Field() ? ? totalNumberInPlan = scrapy.Field() ? ? majorName = scrapy.Field() ? ? categoryName = scrapy.Field() ? ? numberInPlan = scrapy.Field() ? ? note = scrapy.Field() ? ?
這里的Field表示其在Scrapy爬取的實體字段,無關(guān)乎類型。
定義Pipelines
from scrapy.exporters import CsvItemExporter class EnrolldataPipeline(object): ? ? def open_spider(self, spider): ? ? ? ? self.file = open("/home/bladestone/enrolldata.csv", "wb") ? ? ? ? self.exporter = CsvItemExporter(self.file, ? ? ?? ? ? ? ? fields_to_export=["schoolName", "currentBatch", "totalNumberInPlan"]) ? ? ? ? self.exporter.start_exporting() ? ? def process_item(self, item, spider): ? ? ? ? self.exporter.export_item(item) ? ? ? ? return item ? ? def close_spider(self, spider): ? ? ? ? self.exporter.finish_exporting() ? ? ? ? self.file.close()
這里使用了scrapy自帶的CsvItemExporter存儲爬取的結(jié)果。
open_spider()和close_spider()兩個方法都來在spider啟動和結(jié)束的時候,執(zhí)行一些初始化和清理工作,對于pipeline操作而言:
open_spider()
: 執(zhí)行文件創(chuàng)建,然后初始化exporter,并啟動start_exporting(),開始接收Itemclose_spider()
: 結(jié)束exporter的exporting,關(guān)閉文件流。export_item()
:用來將item保存到輸出結(jié)果中。
process_item()為pipeline中定義的方法,在pipeline在settings.py中注冊之后,將會被調(diào)用。
注冊pipeline
在settings.py文件中注冊pipeline:
ITEM_PIPELINES = { ‘enrolldata.pipelines.EnrolldataPipeline': 300, }
spider中返回item
在spider中一般通過yield的方式實現(xiàn)異步返回結(jié)果,此為spider中定義的響應(yīng)處理方法。
具體的示例如下:
def parse_data(): ? ? item = EnrolldataItem() ? ? item['majorName'] = major_name ? ? item['categoryName'] = major_category ? ? item['numberInPlan'] = major_number ? ? item['note'] = major_note ? ? item['schoolName'] = school_name ? ? item['currentBatch'] = current_batch ? ? item['totalNumberInPlan'] = total_number ? ? yield item
執(zhí)行crawler
scrapy crawl enrolldata
enrolldata為項目的名稱。
總結(jié)
在Scrapy中提供了多種結(jié)果輸出方式,目前支持的有: xml, json, csv, pickle等多種方式,對于數(shù)據(jù)的支持也是非常方便的,這方面的內(nèi)容將在后續(xù)的內(nèi)容中進(jìn)行詳細(xì)介紹。
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
Python OpenCV實現(xiàn)鼠標(biāo)畫框效果
這篇文章主要為大家詳細(xì)介紹了Python OpenCV實現(xiàn)鼠標(biāo)畫框效果,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2019-08-08Python文件操作,open讀寫文件,追加文本內(nèi)容實例
本篇文章主要介紹了Python文件操作,open讀寫文件,追加文本內(nèi)容,具有一定的參考價值,有需要的可以了解一下。2016-12-12Python?Pyramid框架應(yīng)用場景及高級特性實戰(zhàn)
Pyramid是一個靈活且強(qiáng)大的Python?web框架,廣泛用于構(gòu)建各種規(guī)模的Web應(yīng)用程序,本文將深度探索Pyramid框架,介紹其核心概念、應(yīng)用場景以及一些高級特性2023-12-12運(yùn)行獨立 pyspark 時出現(xiàn) Windows 錯誤解決辦法
在本篇文章里小編給大家分享的是一篇關(guān)于運(yùn)行獨立 pyspark 時出現(xiàn) Windows 錯誤解決辦法,對此有需求的方法可以參考下。2021-12-12