Scrapy 教程(十)-管道与数据库
Scrapy 框架將爬取的數(shù)據(jù)通過(guò)管道進(jìn)行處理,即 pipelines.py 文件。
?
管道處理流程
一、定義 item
item 表示的是數(shù)據(jù)結(jié)構(gòu),定義了數(shù)據(jù)包括哪些字段
class TianqiItem(scrapy.Item):# define the fields for your item here like: city = scrapy.Field() # 城市date = scrapy.Field() # 日期hour = scrapy.Field() # 小時(shí)day = scrapy.Field() # 白天寫(xiě)法比較固定,不可隨意更改;注意沒(méi)有return
?
二、在爬蟲(chóng)中生成 item
爬蟲(chóng)組件必須將數(shù)據(jù)按 item 的結(jié)構(gòu)進(jìn)行組織
item['city'] = response.xpath('//a[@id="lastBread"]//text()').extract_first()[:-4] item['date'] = '%s-%s-%s'%(year, month, day) item['hour'] = hour注意最終必須? return item;
而且可以 返回多個(gè) item,return item, item2,在某管道中,如果用了 item的key,就自動(dòng)選擇有這個(gè)key的item,否則,所有item都會(huì)經(jīng)過(guò)該處理。
?
三、在管道中處理
1. 爬蟲(chóng)生成的 item 自動(dòng)進(jìn)入管道;
2. 管道會(huì)判斷 流入的數(shù)據(jù) 的類(lèi)型 是否是 item;【即 item.py 中定義的類(lèi)型】
3. 如果是 item 類(lèi)型,進(jìn)行后續(xù)處理,否則,忽略;
4. 返回 item,【必須返回,切記】【返回的 item 流入下一個(gè)管道,或者告訴引擎,處理完畢,否則引擎會(huì)阻塞】
5. 爬取下一個(gè)
class TianqiPipeline(object):def __init__(self):self.f = open('save.txt', 'ab')def process_item(self, item, spider):print(item)self.f.write(str(dict(item)))return itemdef close_spider(self, spider):self.f.close()class RedisPipeline(object):def open_spider(self, spider):host = spider.settings.get('REDIS_HOST', 'localhost')port = spider.settings.get('REDIS_PORT', 6379)db = spider.settings.get('REDIS_DB_INDEX', 0)self.redis_con = redis.StrictRedis(host=host, port=port, db=db)def process_item(self, item, spider):self.redis_con.hmset('%s:%s:%s'%(item['city'], item['date'], item['hour']), dict(item))return itemdef close_spider(self, spider):self.redis_con.connection_pool.disconnect()代碼解釋
必選方法:process_item,負(fù)責(zé)處理數(shù)據(jù)
可選方法:初始化,只在爬蟲(chóng)啟動(dòng)時(shí)進(jìn)行初始化
可選方法:open_spider,在開(kāi)始爬取數(shù)據(jù)之前被調(diào)用
可選方法:close_spider,爬取完數(shù)據(jù)后被調(diào)用
可選方法:from_crawler,獲取配置
?
mongodb 示例,包含了上述方法
首先執(zhí)行 from_crawler 獲取配置,在 open_spider 中創(chuàng)建數(shù)據(jù)庫(kù)連接
?
四、啟動(dòng)管道
在settings中配置即可
ITEM_PIPELINES = {'tianqi.pipelines.TianqiPipeline': 300,'tianqi.pipelines.RedisPipeline': 301, }?
存在問(wèn)題
上面這種方式 會(huì)作用于所有爬蟲(chóng);
我們可以在 管道中 判斷 是哪個(gè)爬蟲(chóng),根據(jù) spider 參數(shù),或者 根據(jù) item 中的 key,但這種方法很冗余;
更好的做法是在 spider類(lèi) 中配置 custom_settings 對(duì)象
# 類(lèi)屬性 custom_settings = {'ITEM_PIPELINES': {'getProxy.pipelines.GetproxyPipeline': 300, }}?
數(shù)據(jù)庫(kù)存儲(chǔ)
管道可以實(shí)現(xiàn)任何形式的存儲(chǔ),包括文件、數(shù)據(jù)庫(kù)等;
而且可以存入各種數(shù)據(jù)庫(kù),如 sqlite、mysql、mongoDB、redis;
上面的例子實(shí)現(xiàn)了 redis、mongodb 的存儲(chǔ),其他大同小異,以后有機(jī)會(huì)再更新。
轉(zhuǎn)載于:https://www.cnblogs.com/yanshw/p/10919052.html
總結(jié)
以上是生活随笔為你收集整理的Scrapy 教程(十)-管道与数据库的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 【qq语音获取好友ip】wireshar
- 下一篇: mysql优化三