Scrapy學(xué)習(xí)筆記(8)-使用signals來監(jiān)控spider的狀態(tài)

場景介紹

有時(shí)候我們需要在spider啟動或者結(jié)束的時(shí)候執(zhí)行一些特定的操作朋譬,比如說記錄日志之類的,在scrapy中我們可以使用signals來實(shí)現(xiàn)微驶。

主要實(shí)現(xiàn)代碼如下:

# -*- coding: utf-8 -*-from scrapy import signalsfrom scrapy.xlib.pydispatch import dispatcherfrom scrapy.linkextractors import LinkExtractorfrom scrapy.spiders import CrawlSpider, Rulefrom items import IpProxyPoolItemfrom model.spider_running_log import SpiderCrawlLogfrom model import loadSessionfrom datetime import datetimeclass ProxySpiderSpider(CrawlSpider):? ? name = 'MagicSpider'? ? def __init__(self,rule):? ? ? ? #spider啟動信號和spider_opened函數(shù)綁定? ? ? ? dispatcher.connect(self.spider_opened, signals.spider_opened)? ? ? ? #spider關(guān)閉信號和spider_spider_closed函數(shù)綁定? ? ? ? dispatcher.connect(self.spider_closed, signals.spider_closed)? ? ? ? self.rule = rule

? ? ? ? self.name = rule.name

? ? ? ? self.allowed_domains = rule.allowed_domains.split(',')? ? ? ? self.start_urls = rule.start_urls.split(',')? ? ? ? rule_list = []? ? ? ? # 添加`下一頁`的規(guī)則? ? ? ? if len(rule.next_page):? ? ? ? ? ? rule_list.append(Rule(LinkExtractor(restrict_xpaths=rule.next_page), follow=True))? ? ? ? rule_list.append(Rule(LinkExtractor(? ? ? ? ? ? allow=rule.allow_url.split(','),? ? ? ? ? ? unique=True),? ? ? ? ? ? follow=True,? ? ? ? ? ? callback='parse_item'))? ? ? ? self.rules = tuple(rule_list)? ? ? ? super(ProxySpiderSpider, self).__init__()? ? #spider關(guān)閉時(shí)的邏輯? ? def spider_closed(self, spider):? ? ? ? print "spider is closed!"? ? ? ? session = loadSession()? ? ? ? log = session.query(SpiderCrawlLog).filter(SpiderCrawlLog.spiderID == self.rule.id,? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? SpiderCrawlLog.endTime == None? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ).first()? ? ? ? log.endTime = datetime.now().strftime("%Y-%m-%d %H:%M:%S")? ? ? ? log.status = "closed"? ? ? ? session.commit()? ? #spider啟動時(shí)的邏輯? ? def spider_opened(self, spider):? ? ? ? print "spider is running!"? ? ? ? item = SpiderCrawlLog(? ? ? ? ? ? ? ? ? ? ? ? ? ? ? spiderID=self.rule.id,? ? ? ? ? ? ? ? ? ? ? ? ? ? ? spiderName=self.rule.name,? ? ? ? ? ? ? ? ? ? ? ? ? ? ? status="Running...",? ? ? ? ? ? ? ? ? ? ? ? ? ? ? startTime=datetime.now().strftime("%Y-%m-%d %H:%M:%S"),? ? ? ? ? ? ? ? ? ? ? ? ? ? ? endTime=None,? ? ? ? ? ? ? ? ? ? ? ? ? ? ? pages=0,? ? ? ? ? ? ? ? ? ? ? ? ? ? ? items=0? ? ? ? ? ? ? ? ? ? ? ? ? ? ? )? ? ? ? session = loadSession()? ? ? ? log = session.query(SpiderCrawlLog).filter(? ? ? ? ? ? SpiderCrawlLog.spiderID == self.rule.id,? ? ? ? ? ? SpiderCrawlLog.endTime == None)? ? ? ? # 查詢當(dāng)前spider是否有未結(jié)束的日志? ? ? ? if log.count() == 0 :? ? ? ? ? ? session.add(item)? ? ? ? ? ? session.commit()? ? ? ? else:? ? ? ? ? ? pass? ? def parse_item(self, response):? ? ? ? # print 'Hi, this is an item page! %s' % response.url? ? ? ? #print response.body? ? ? ? session = loadSession()? ? ? ? log = session.query(SpiderCrawlLog).filter(SpiderCrawlLog.spiderID == self.rule.id,? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? SpiderCrawlLog.endTime == None).first()? ? ? ? log.pages = int(log.pages) + 1? ? ? ? session.commit()? ? ? ? item=IpProxyPoolItem()? ? ? ? if len(self.rule.loop_xpath):? ? ? ? ? ? # print 'Find %d items!'% len(response.xpath(self.rule.loop_xpath))? ? ? ? ? ? for proxy in response.xpath(self.rule.loop_xpath):? ? ? ? ? ? ? ? if len(self.rule.ip_xpath):? ? ? ? ? ? ? ? ? ? tmp_ip = proxy.xpath(self.rule.ip_xpath).extract_first()? ? ? ? ? ? ? ? ? ? ip = tmp_ip.strip() if tmp_ip is not None else ""? ? ? ? ? ? ? ? else:? ? ? ? ? ? ? ? ? ? ip = ""? ? ? ? ? ? ? ? if len(self.rule.port_xpath):? ? ? ? ? ? ? ? ? ? tmp_port = proxy.xpath(self.rule.port_xpath).extract_first()? ? ? ? ? ? ? ? ? ? port = tmp_port.strip() if tmp_port is not None else ""? ? ? ? ? ? ? ? else:? ? ? ? ? ? ? ? ? ? port = ""? ? ? ? ? ? ? ? if len(self.rule.location1_xpath):? ? ? ? ? ? ? ? ? ? tmp_location1 = proxy.xpath(self.rule.location1_xpath).extract_first()? ? ? ? ? ? ? ? ? ? location1 = tmp_location1.strip() if tmp_location1 is not None else ""? ? ? ? ? ? ? ? else:? ? ? ? ? ? ? ? ? ? location1 = ""? ? ? ? ? ? ? ? if len(self.rule.location2_xpath):? ? ? ? ? ? ? ? ? ? tmp_location2 = proxy.xpath(self.rule.location2_xpath).extract_first()? ? ? ? ? ? ? ? ? ? location2 = tmp_location2.strip() if tmp_location2 is not None else ""? ? ? ? ? ? ? ? else:? ? ? ? ? ? ? ? ? ? location2 = ""? ? ? ? ? ? ? ? if len(self.rule.lifetime_xpath):? ? ? ? ? ? ? ? ? ? tmp_lifetime = proxy.xpath(self.rule.lifetime_xpath).extract_first()? ? ? ? ? ? ? ? ? ? lifetime = tmp_lifetime.strip() if tmp_lifetime is not None else ""? ? ? ? ? ? ? ? else:? ? ? ? ? ? ? ? ? ? lifetime = ""? ? ? ? ? ? ? ? if len(self.rule.lastcheck_xpath):? ? ? ? ? ? ? ? ? ? tmp_lastcheck = proxy.xpath(self.rule.lastcheck_xpath).extract_first()? ? ? ? ? ? ? ? ? ? lastcheck = tmp_lastcheck.strip() if tmp_lastcheck is not None else ""? ? ? ? ? ? ? ? else:? ? ? ? ? ? ? ? ? ? lastcheck = ""? ? ? ? ? ? ? ? if len(self.rule.level_xpath):? ? ? ? ? ? ? ? ? ? tmp_level = proxy.xpath(self.rule.level_xpath).extract_first()? ? ? ? ? ? ? ? ? ? level = tmp_level.strip() if tmp_level is not None else ""? ? ? ? ? ? ? ? else:? ? ? ? ? ? ? ? ? ? level = ""? ? ? ? ? ? ? ? if len(self.rule.type_xpath):? ? ? ? ? ? ? ? ? ? tmp_type = proxy.xpath(self.rule.type_xpath).extract_first()? ? ? ? ? ? ? ? ? ? type = tmp_type.strip() if tmp_type is not None else ""? ? ? ? ? ? ? ? else:? ? ? ? ? ? ? ? ? ? type = ""? ? ? ? ? ? ? ? if len(self.rule.speed_xpath):? ? ? ? ? ? ? ? ? ? tmp_speed = proxy.xpath(self.rule.speed_xpath).extract_first()? ? ? ? ? ? ? ? ? ? speed = tmp_speed.strip() if tmp_speed is not None else ""? ? ? ? ? ? ? ? else:? ? ? ? ? ? ? ? ? ? speed = ""? ? ? ? ? ? ? ? item['ip_port']=(":".join([ip,port])) if len(port) else ip

? ? ? ? ? ? ? ? item['type']=type

? ? ? ? ? ? ? ? item['level']=level

? ? ? ? ? ? ? ? item['location']=(" ".join([location1,location2])) if location2 is not None and len(location2) else location1

? ? ? ? ? ? ? ? item['speed']=speed

? ? ? ? ? ? ? ? item['lifetime']=lifetime

? ? ? ? ? ? ? ? item['lastcheck']=lastcheck

? ? ? ? ? ? ? ? item['rule_id']=self.rule.id

? ? ? ? ? ? ? ? item['source']=response.url

? ? ? ? ? ? ? ? yield item

應(yīng)用截圖:

使用signals機(jī)制來插入日志并實(shí)時(shí)更新spider的運(yùn)行和數(shù)據(jù)爬取狀態(tài)

更多原創(chuàng)文章磅叛,盡在金筆頭博客

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市判耕,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌厨内,老刑警劉巖祈秕,帶你破解...
    沈念sama閱讀 221,888評論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件渺贤,死亡現(xiàn)場離奇詭異雏胃,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)志鞍,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,677評論 3 399
  • 文/潘曉璐 我一進(jìn)店門瞭亮,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人固棚,你說我怎么就攤上這事统翩。” “怎么了此洲?”我有些...
    開封第一講書人閱讀 168,386評論 0 360
  • 文/不壞的土叔 我叫張陵厂汗,是天一觀的道長。 經(jīng)常有香客問我呜师,道長娶桦,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 59,726評論 1 297
  • 正文 為了忘掉前任汁汗,我火速辦了婚禮衷畦,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘知牌。我一直安慰自己祈争,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 68,729評論 6 397
  • 文/花漫 我一把揭開白布角寸。 她就那樣靜靜地躺著菩混,像睡著了一般。 火紅的嫁衣襯著肌膚如雪扁藕。 梳的紋絲不亂的頭發(fā)上墨吓,一...
    開封第一講書人閱讀 52,337評論 1 310
  • 那天,我揣著相機(jī)與錄音纹磺,去河邊找鬼帖烘。 笑死,一個(gè)胖子當(dāng)著我的面吹牛橄杨,可吹牛的內(nèi)容都是我干的秘症。 我是一名探鬼主播照卦,決...
    沈念sama閱讀 40,902評論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼乡摹!你這毒婦竟也來了役耕?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,807評論 0 276
  • 序言:老撾萬榮一對情侶失蹤聪廉,失蹤者是張志新(化名)和其女友劉穎瞬痘,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體板熊,經(jīng)...
    沈念sama閱讀 46,349評論 1 318
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡框全,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,439評論 3 340
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了干签。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片津辩。...
    茶點(diǎn)故事閱讀 40,567評論 1 352
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖容劳,靈堂內(nèi)的尸體忽然破棺而出喘沿,到底是詐尸還是另有隱情,我是刑警寧澤竭贩,帶...
    沈念sama閱讀 36,242評論 5 350
  • 正文 年R本政府宣布蚜印,位于F島的核電站,受9級特大地震影響留量,放射性物質(zhì)發(fā)生泄漏窄赋。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,933評論 3 334
  • 文/蒙蒙 一肪获、第九天 我趴在偏房一處隱蔽的房頂上張望寝凌。 院中可真熱鬧,春花似錦孝赫、人聲如沸较木。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,420評論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽伐债。三九已至,卻和暖如春致开,著一層夾襖步出監(jiān)牢的瞬間峰锁,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,531評論 1 272
  • 我被黑心中介騙來泰國打工双戳, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留虹蒋,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 48,995評論 3 377
  • 正文 我出身青樓,卻偏偏與公主長得像魄衅,于是被迫代替她去往敵國和親峭竣。 傳聞我的和親對象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,585評論 2 359

推薦閱讀更多精彩內(nèi)容