配置 settings.py 啟用自定義 IP 代理中間件
DOWNLOADER_MIDDLEWARES
設置自定義 IP 代理中間件優先級高於系統 IP 代理中間件
DOWNLOADER_MIDDLEWARES = { 'quotes.middlewares.QuotesDownloaderMiddleware': 543, # 'quotes.middlewares.UserAgentMiddlewares': 543, }
收集可用的 IP 代理,構建 IP 代理池
在 settings.py 中定義IP代理數組
IPPools = [ {"ipaddr":"124.205.155.149:9090"}, {"ipaddr":"119.23.79.199:3128"}, {"ipaddr":"120.26.208.102:88"}, {"ipaddr":"111.231.12.253:1080"}, ]
這些IP可以從這個幾個網站獲取:快代理、代理66、有代理、西刺代理、guobanjia。如果出現像下面這種提示:"由於連接方在一段時間后沒有正確答復或連接的主機沒有反應,連接嘗試失敗"或者是這種," 由 於目標計算機積極拒絕,無法連接。". 那就是IP的問題,更換就行了。
middlewares.py 中添加 UserAgentMiddlewares 類
重寫 process_request() 方法
使用 random 庫的 choice 方法隨機從 IP 中選取代理 IP
設置 request 的 meta 屬性設置代理
def process_request(self, request, spider): thisip = random.choice(IPPools) request.meta['proxy'] = 'http://' + thisip['ipaddr'] print('this is ip:%s'%thisip['ipaddr'])