import random
from collections import defaultdict
from scrapy import signals
from twisted.internet.error import ConnectionRefusedError, TimeoutError
class QczjproDownloaderMiddleware(object):
# Not all methods need to be defined. If a method is not defined,
# scrapy acts as if the downloader middleware does not modify the
# passed objects.
# 初始化數(shù)據(jù)
def __init__(self, settings):
self.settings = settings
self.ips = settings.getlist("IPS")
#錯(cuò)誤記錄 轉(zhuǎn)成字典結(jié)構(gòu)(value是int類型) 默認(rèn)為0
self.proxy_error_stats = defaultdict(int)
@classmethod
def from_crawler(cls, crawler):
# This method is used by Scrapy to create your spiders.
# 實(shí)例化的時(shí)候垄琐,把settings給init函數(shù)
s = cls(crawler.settings)
# 實(shí)例化的時(shí)候注冊(cè)了個(gè)信號(hào)
crawler.signals.connect(s.spider_opened, signal=signals.spider_opened)
return s
def process_request(self, request, spider):
# Called for each request that goes through the downloader
# middleware.
# Must either:
# - return None: continue processing this request
# - or return a Response object
# - or return a Request object
# - or raise IgnoreRequest: process_exception() methods of
# installed downloader middleware will be called
# 加代理IP
if "proxy" not in request.meta:
proxy = random.choice(self.ips)
# proxy = random.choice(self.cookies)
# proxy = random.choice(self.headers)
print(proxy, "---------------------------------")
request.meta['proxy'] = proxy
# else:
# print(request.meta["proxy"])
return None
def process_response(self, request, response, spider):
# Called with the response returned from the downloader.
# Must either;
# - return a Response object
# - return a Request object
# - or raise IgnoreRequest
status_code = response.status
if status_code in [403, 500, 404]:
ip = request.meta["proxy"]
# 統(tǒng)計(jì)某個(gè)IP的錯(cuò)誤次數(shù)
self.proxy_error_stats[ip] += 1
# 如果大于我們約定的五次,那就刪IP
if self.proxy_error_stats[ip] > 5:
# self.ips.remove(ip)
self.remove_fail_ip(ip)
# 去掉這個(gè)請(qǐng)求的meta的proxy
del request.meta["proxy"]
return request
return response
def process_exception(self, request, exception, spider):
# Called when a download handler or a process_request()
# (from other downloader middleware) raises an exception.
# Must either:
# - return None: continue processing this exception
# - return a Response object: stops process_exception() chain
# - return a Request object: stops process_exception() chain
# 當(dāng)出現(xiàn)跟代理IP有關(guān)系的異常的時(shí)候
if isinstance(exception, (ConnectionRefusedError, TimeoutError)):
# self.ips 去掉這個(gè)無(wú)效的IP
ip = request.meta["proxy"]
# self.ips.remove(ip)
self.remove_fail_ip(ip)
# 去掉這個(gè)請(qǐng)求的meta的proxy
del request.meta["proxy"]
# 重新安排下載
return request
def remove_fail_ip(self, ip):
if ip in self.ips:
self.ips.remove(ip)
def spider_opened(self, spider):
spider.logger.info('Spider opened: %s' % spider.name)
在Scrapy中間件里面寫ip代理池相關(guān)
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
- 文/潘曉璐 我一進(jìn)店門赏壹,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái),“玉大人衔沼,你說(shuō)我怎么就攤上這事卡儒。” “怎么了俐巴?”我有些...
- 文/不壞的土叔 我叫張陵骨望,是天一觀的道長(zhǎng)。 經(jīng)常有香客問(wèn)我欣舵,道長(zhǎng)擎鸠,這世上最難降的妖魔是什么? 我笑而不...
- 正文 為了忘掉前任缘圈,我火速辦了婚禮劣光,結(jié)果婚禮上袜蚕,老公的妹妹穿的比我還像新娘。我一直安慰自己绢涡,他們只是感情好牲剃,可當(dāng)我...
- 文/花漫 我一把揭開(kāi)白布。 她就那樣靜靜地躺著雄可,像睡著了一般凿傅。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上数苫,一...
- 那天聪舒,我揣著相機(jī)與錄音,去河邊找鬼虐急。 笑死箱残,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的止吁。 我是一名探鬼主播被辑,決...
- 文/蒼蘭香墨 我猛地睜開(kāi)眼,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼敬惦!你這毒婦竟也來(lái)了盼理?” 一聲冷哼從身側(cè)響起,我...
- 序言:老撾萬(wàn)榮一對(duì)情侶失蹤仁热,失蹤者是張志新(化名)和其女友劉穎榜揖,沒(méi)想到半個(gè)月后,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體抗蠢,經(jīng)...
- 正文 獨(dú)居荒郊野嶺守林人離奇死亡举哟,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
- 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了迅矛。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片妨猩。...
- 正文 年R本政府宣布庐椒,位于F島的核電站,受9級(jí)特大地震影響蚂踊,放射性物質(zhì)發(fā)生泄漏约谈。R本人自食惡果不足惜,卻給世界環(huán)境...
- 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望棱诱。 院中可真熱鬧泼橘,春花似錦、人聲如沸迈勋。這莊子的主人今日做“春日...
- 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)靡菇。三九已至重归,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間镰官,已是汗流浹背提前。 一陣腳步聲響...
- 正文 我出身青樓宙搬,卻偏偏與公主長(zhǎng)得像笨腥,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子勇垛,可洞房花燭夜當(dāng)晚...
推薦閱讀更多精彩內(nèi)容
- 在寫爬蟲的時(shí)候脖母,經(jīng)常會(huì)遇到一個(gè)難題,就是反爬蟲闲孤。反爬蟲策略一般就是檢測(cè)user-agent谆级,IP等等信息,辨別是機(jī)...
- 我們總是斗志昂揚(yáng)抱著書本讼积,與書中的文字來(lái)一場(chǎng)邂逅肥照,來(lái)一場(chǎng)思想的碰撞,總想著自己一直在奮斗的路上勤众∮咭铮可惜,我們總被各種...
- 樓下小店,東西又貴又次窥突,大人無(wú)力吐槽努溃。奈何孩子喜歡呀。 和一個(gè)寶媽邊看孩子邊聊天阻问。誰(shuí)知一不留神梧税,她家娃就不見(jiàn)影子了...
- 01 生活中,除了需要情商、智商贡蓖、財(cái)商曹鸠,我們還需要具備住商。住商是一個(gè)人思維斥铺、審美彻桃、財(cái)富運(yùn)用等能力的綜合體現(xiàn)。 0...