python爬蟲利用代理池更換IP的方法步驟
周日在爬一個(gè)國(guó)外網(wǎng)站的時(shí)候,發(fā)現(xiàn)用協(xié)程并發(fā)請(qǐng)求,并且請(qǐng)求次數(shù)太快的時(shí)候,會(huì)出現(xiàn)對(duì)方把我的服務(wù)器IP封掉的情況。于是網(wǎng)上找了一下開源的python代理池,這里選擇的是star數(shù)比較多的proxy_pool
1. 安裝環(huán)境# 安裝python虛擬環(huán)境, python環(huán)境最好為python3.6,再往上的話,安裝依賴時(shí)會(huì)報(bào)錯(cuò)sudo apt updatesudo apt install python3.6pip3 install virtualenvvirtualenv venv --python=python3.6source venv/bin/activate# 安裝redissudo apt install redis-server# 啟動(dòng)redis serverredis-server 2. 安裝依賴
git clone https://github.com/jhao104/proxy_pool.gitcd proxy_poolpip install -r requirements.txt3. 修改配置文件
# 修改setting.py # 配置API服務(wù)HOST = '0.0.0.0' # IPPORT = 5010 # 監(jiān)聽端口# 配置數(shù)據(jù)庫(kù)# 以下為三個(gè)示例,根據(jù)redis的配置,選擇其中一種即可# 一般啟動(dòng)redis時(shí)如果沒有配置文件,那么選擇第一種即可# 1. Redis IP: 127.0.0.1 Port: 6379DB_CONN = ’redis://@127.0.0.1:6379’# 2. Redis IP: 127.0.0.1 Port: 6379 Password: 123456DB_CONN = ’redis://:123456@127.0.0.1:6379’# 3. Redis IP: 127.0.0.1 Port: 6379 Password: 123456 DB: 15DB_CONN = ’redis://:123456@127.0.0.1:6379/15’ # 配置 ProxyFetcherPROXY_FETCHER = [ 'freeProxy01', # 這里是啟用的代理抓取方法名,所有fetch方法位于fetcher/proxyFetcher.py 'freeProxy02', # ....]4. 啟動(dòng)
# 可以用tmux開三個(gè)窗口# 啟動(dòng)調(diào)度程序python proxyPool.py schedule# 啟動(dòng)webApi服務(wù)python proxyPool.py server5. 測(cè)試
import requestsdef 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 codedef 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爬蟲利用代理池更換IP的方法步驟的文章就介紹到這了,更多相關(guān)python 代理池更換IP內(nèi)容請(qǐng)搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. ASP.NET MVC使用jQuery ui的progressbar實(shí)現(xiàn)進(jìn)度條2. Ajax對(duì)xml信息的接收和處理操作實(shí)例分析3. Jsp中request的3個(gè)基礎(chǔ)實(shí)踐4. Ajax返回值類型與用法實(shí)例分析5. python簡(jiǎn)單實(shí)現(xiàn)9宮格圖片實(shí)例6. 利用Java對(duì)PDF文件進(jìn)行電子簽章的實(shí)戰(zhàn)過(guò)程7. php根據(jù)id生成10位不重復(fù)數(shù)字跟字母混合字符串8. ASP動(dòng)態(tài)include文件9. Java實(shí)戰(zhàn)之實(shí)現(xiàn)一個(gè)好用的MybatisPlus代碼生成器10. Python request中文亂碼問(wèn)題解決方案
