1. 程式人生 > >自己設計代理IP池

自己設計代理IP池

+= use rom n) tex gen 錯誤類型 pro orm

大體思路

使用redis作為隊列,買了一份蘑菇代理,但是這個代理每5秒可以請求一次,我們將IP請求出來,從redis列表隊列的左側插入,要用的時候再從右側取出,請求成功證明該IP是可用的,將該代理IP從左側放回,三次都請求失敗則認為該代理IP已經失效

代碼如下:

import requests
import json
import redis
import time
r = redis.Redis(host=‘127.0.0.1‘, port=6379,db=3)
num = r.llen(‘the_ip‘)
print(num)
while True:
if num<5:
ip = requests.get(‘http://piping.mogumiao.com/proxy/api/get_ip_al?appKey=b9bfb84c7ca34fec9f51b3a9dca147e5&count=2&expiryDate=0&format=1‘).text
print(ip)
code = json.loads(ip)[‘code‘]
if code==‘0‘:
msg = json.loads(ip)[‘msg‘]
for i in msg:
ip = i[‘ip‘]+‘:‘+i[‘port‘]
print(ip)
r.lpush(‘the_ip‘,ip)
num = r.llen(‘the_ip‘)
elif code==‘3001‘:
"提取頻繁,5秒提取一次!"
time.sleep(5)
else:
print(‘調用IP接口錯誤,錯誤類型為‘+code)
else:
print(‘IP池已經滿了‘)
num = r.llen(‘the_ip‘)
time.sleep(3)

上面這些代碼是保證redis代理IP池裏始終有5個左右的代理IP
import requests
import json
import redis
import time
from lxml import etree
r = redis.Redis(host=‘127.0.0.1‘, port=6379,db=3)
def get_source(url,header,data=None):
ip = r.rpop(‘the_ip‘).decode(‘utf8‘)
print(‘提取ip‘,ip)
if data==None:
n = 0
while True:
try:
source = requests.get(url,headers=header,proxies={‘http‘:ip},timeout=5).content
r.lpush(‘the_ip‘,ip)
print(‘請求成功返還IP‘,ip)
return source
except:
n+=1
print(‘請求失敗‘+str(n)+‘次‘)
if n==3:
return get_source(url,header)

else:
source = requests.get(url, headers=header, proxies={‘http‘: ip},data=data).content
return source


header = {‘User-Agent‘: "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.117 Safari/537.36}"
}
while True:
source = get_source(‘http://www.ip111.cn/‘,header).decode(‘utf8‘)
show = etree.HTML(source).xpath(‘//tr[2]/td[2]/text()‘)
print(show)

上面的代理是循環請求查看當前IP的網址,從而看出代理IP的變化。每次請求都是輪著使用代理的,可以是代理用更長時間而不必擔心老用一個代理IP被封了

自己設計代理IP池