Python爬虫之ip代理池

时间:2022-03-16 13:44:39

 

    可能在学习爬虫的时候,遇到很多的反爬的手段,封ip 就是其中之一。

    对于封IP的网站。需要很多的代理IP,去买代理IP,对于初学者觉得没有必要,每个卖代理IP的网站有的提供了免费IP,可是又很少,写了个IP代理池 。学习应该就够了

    ip代理池:

1,在各大网站爬去免费代理ip
2,检查ip可用 可用存入数据库1和2
3,在数据库1中拿出少量代理ip存入数据库2(方便维护)
4,定时检查数据库1和数据库2的代理数量,以及是否可用
5,调用端口

1,在各大网站爬去免费代理ip
 
 1 def IPList_61():
 2   for q in [1,2]:
 3       url='http://www.66ip.cn/'+str(q)+'.html'
 4       html=Requestdef.get_page(url)
 5       if html!=None:
 6           #print(html)
 7           iplist=BeautifulSoup(html,'lxml')
 8           iplist=iplist.find_all('tr')
 9           i=2
10           for ip in iplist:
11              if i<=0:
12                  loader=''
13                  #print(ip)
14                  j=0
15                  for ipport in ip.find_all('td',limit=2):
16                      if j==0:
17                         loader+=ipport.text.strip()+':'
18                      else:
19                          loader+=ipport.text.strip()
20                      j=j+1
21                  Requestdef.inspect_ip(loader)
22              i=i-1
23       time.sleep(1)
 

多写几个这样的方法

Python爬虫之ip代理池

2,检查ip可用 可用存入数据库1,和2

3,在数据库1中拿出少量代理ip存入数据库2(方便维护)
Python爬虫之ip代理池Python爬虫之ip代理池
 1 def inspect_ip(ipprot):
 2     time.sleep(1)
 3     herder={
 4         "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36",
 5         'Accept-Encoding':'gzip, deflate',
 6         'Accept-Language':'zh-CN,zh;q=0.9',
 7         'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
 8         'Upgrade-Insecure-Requests':'1'
 9 
10     }
11 
12     url='https://www.baidu.com'
13     proxies = { "http": "http://"+str(ipprot) }
14     request=requests.get(url,headers=herder,proxies=proxies)
15     if request.status_code==200:
16         print('可用代理'+ipprot)
17         if Db.r.llen('Iplist')<=50:
18            Db.add_ip(ipprot)
19         #Alt.iplist.append(ipprot)
20 
21         else:
22            Db.add_ips(ipprot)
23     else:
24         print('不可用代理'+ipprot)
View Code
 

我这里是用的www.baidu.com检测的 给主IP的数据库长度是50 (太多了不好维护)

 
4,定时检查数据库1和数据库2的代理数量,以及是否可用


#检查ip池数量
def time_ip():

    while True:
        time.sleep(5)
        Db.act_lenip()

#检查备用池数量
def time_ips():
    while True:
        time.sleep(30)
#当备用池数量小于100 再次获取 if Db.len_ips()<100: print('填数据') Acting_ip.iplist() #程序入口 if __name__ == '__main__': t1=threading.Thread(target=time_ip) t1.start() t2=threading.Thread(target=time_ips) t2.start() t1.join() t2.join()

  给他2个线程  

Db.py

Python爬虫之ip代理池Python爬虫之ip代理池
 1 #coding:utf-8
 2 import redis
 3 import Requestdef
 4 r = redis.Redis(host='127.0.0.1', port=6379)#host后的IP是需要连接的ip,本地是127.0.0.1或者localhost
 5 #主ip池
 6 def add_ip(ip):
 7      r.lpush('Iplist',ip)
 8 #备用ip池
 9 def add_ips(ip):
10      r.lpush('Iplists',ip)
11 #备用ip池第一个开始取出
12 def app_ips():
13      i=str(r.lindex('Iplists',1),encoding='utf-8')
14      r.lrem('Iplists',i,num=0)
15      return i
16 def len_ips():
17     return r.llen('Iplists')
18 def len_ip():
19     return r.llen('Iplist')
20 #第一个开始取出
21 def app_ip():
22      i=str(r.lpop('Iplist'),encoding='utf-8')
23      return i
24 #取出从最后一个开始
25 def rem_ip():
26     i=str(r.rpop('Iplist'),encoding='utf-8')
27     return i
28 #检查主ip池
29 def act_db():
30     for i in range(int(r.llen('Iplist')/2)):
31        Requestdef.inspect_ip(rem_ip())
32 
33 #如果ip池数量少于25个 则填满
34 def act_lenip():
35     if r.llen('Iplist')<25:
36         print('填ip')
37         while r.llen('Iplist')<=50:
38           Requestdef.inspect_ip(app_ips())
Db.py

 


5,调用端口 使用flask库创建接口
Python爬虫之ip代理池Python爬虫之ip代理池
 1 from flask import Flask
 2 import Db
 3 
 4 app = Flask(__name__)
 5 
 6 @app.route('/', methods=['GET'])
 7 def home():
 8     return 'What is?'
 9 
10 @app.route('/get', methods=['GET'])
11 def homsse():
12     return Db.app_ip()
13 #线程池数量
14 @app.route('/count', methods=['GET'])
15 def homsssse():
16     return str(Db.len_ip())
17 app.run(debug=True)
API.PY
 

就完成了

 运行api

Python爬虫之ip代理池

 

Python爬虫之ip代理池

数据库里面的 Iplist为主Ip池 iplist 为备用ip池

 

 Python爬虫之ip代理池

 

用get调用 用一次就删一个

Python爬虫之ip代理池

Python爬虫之ip代理池

小白代码