Python爬蟲之ip代理池

 

    可能在學習爬蟲的時候,遇到不少的反爬的手段,封ip 就是其中之一。html

    對於封IP的網站。須要不少的代理IP,去買代理IP,對於初學者以爲沒有必要,每一個賣代理IP的網站有的提供了免費IP,但是又不多,寫了個IP代理池 。學習應該就夠了python

    ip代理池:web

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)
 

多寫幾個這樣的方法redis

2,檢查ip可用 可用存入數據庫1,和2

3,在數據庫1中拿出少許代理ip存入數據庫2(方便維護)
 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)

  

 

我這裏是用的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個線程  flask

Db.pyapi

 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())

  

 


5,調用端口 使用flask庫建立接口
 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)

  

 

就完成了app

 運行api學習

 

數據庫裏面的 Iplist爲主Ip池 iplist 爲備用ip池網站

 

 

 

用get調用 用一次就刪一個

小白代碼
相關文章
相關標籤/搜索