周日在爬一個(gè)國(guó)外網(wǎng)站的時(shí)候,發(fā)現(xiàn)用協(xié)程并發(fā)請(qǐng)求,并且請(qǐng)求次數(shù)太快的時(shí)候,會(huì)出現(xiàn)對(duì)方把我的服務(wù)器IP封掉的情況。于是網(wǎng)上找了一下開(kāi)源的python代理池,這里選擇的是star數(shù)比較多的proxy_pool
# 安裝python虛擬環(huán)境, python環(huán)境最好為python3.6,再往上的話,安裝依賴時(shí)會(huì)報(bào)錯(cuò) sudo apt update sudo apt install python3.6 pip3 install virtualenv virtualenv venv --python=python3.6 source venv/bin/activate # 安裝redis sudo apt install redis-server # 啟動(dòng)redis server redis-server
git clone https://github.com/jhao104/proxy_pool.git cd proxy_pool pip install -r requirements.txt
# 修改setting.py # 配置API服務(wù) HOST = "0.0.0.0" # IP PORT = 5010 # 監(jiān)聽(tīng)端口 # 配置數(shù)據(jù)庫(kù) # 以下為三個(gè)示例,根據(jù)redis的配置,選擇其中一種即可 # 一般啟動(dòng)redis時(shí)如果沒(méi)有配置文件,那么選擇第一種即可 # 1. Redis IP: 127.0.0.1 Port: 6379 DB_CONN = 'redis://@127.0.0.1:6379' # 2. Redis IP: 127.0.0.1 Port: 6379 Password: 123456 DB_CONN = 'redis://:123456@127.0.0.1:6379' # 3. Redis IP: 127.0.0.1 Port: 6379 Password: 123456 DB: 15 DB_CONN = 'redis://:123456@127.0.0.1:6379/15' # 配置 ProxyFetcher PROXY_FETCHER = [ "freeProxy01", # 這里是啟用的代理抓取方法名,所有fetch方法位于fetcher/proxyFetcher.py "freeProxy02", # .... ]
# 可以用tmux開(kāi)三個(gè)窗口 # 啟動(dòng)調(diào)度程序 python proxyPool.py schedule # 啟動(dòng)webApi服務(wù) python proxyPool.py server
import requests def get_proxy(): return requests.get("http://127.0.0.1:5010/get/").json() def delete_proxy(proxy): requests.get("http://127.0.0.1:5010/delete/?proxy={}".format(proxy)) # your spider code def getHtml(): # .... retry_count = 5 proxy = get_proxy().get("proxy") while retry_count > 0: try: html = requests.get('http://www.example.com', proxies={"http": "http://{}".format(proxy)}) # 使用代理訪問(wèn) return html except Exception: retry_count -= 1 # 刪除代理池中代理 delete_proxy(proxy) return None
更多的用法和文檔請(qǐng)參考:document 和 https://github.com/jhao104/proxy_pool
到此這篇關(guān)于python爬蟲(chóng)利用代理池更換IP的方法步驟的文章就介紹到這了,更多相關(guān)python 代理池更換IP內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
標(biāo)簽:哈爾濱 郴州 大慶 合肥 平頂山 海南 烏蘭察布 烏蘭察布
巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《python爬蟲(chóng)利用代理池更換IP的方法步驟》,本文關(guān)鍵詞 python,爬蟲(chóng),利用,代理,池,;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問(wèn)題,煩請(qǐng)?zhí)峁┫嚓P(guān)信息告之我們,我們將及時(shí)溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無(wú)關(guān)。