博主写在前面的话:
早就有了搭建自己的动态IP池的想法,怎奈技术不够,看过好多大佬的动态IP池,觉得大佬们写的IP池太成熟了,不适合我们这些菜鸟入门。这篇博客的受众是想搭建自己动态IP池的初学者,大佬级别的自动跳过本文。
搭建思路分析:
我的IP池是用Python和redis数据库搭建的,这里只演示了抓取http协议的IP,抓取动态IP选取的对象为快代理,网站为:https://www.kuaidaili.com/free/inha/,抓取之后将可用的IP存入redis中,并实时监测redis中的IP是否可用,若可用留下,若不可用就剔除。用flask写了一个接口API,将redis中的IP以网页的暴露出来以便调用。
代码如下:首先我写了一个爬取快代理IP的crawl_IP.py文件如下:
import requests
from bs4 import BeautifulSoup
from fake_useragent import UserAgent
import time
import bs4
class crawl:
def page_kuai(page,r):
ua = UserAgent()
headers={'User-Agent':ua.random}
html=requests.get('https://www.kuaidaili.com/free/inha/'+str(page),headers=headers)#删除作者参数 ,verify=False
if html.status_code == 200:
Soup=BeautifulSoup(html.text,'lxml')
tbody=Soup.find('tbody')
if isinstance(tbody,bs4.element.Tag):
tr_list=tbody.find_all('tr')
for tr in tr_list:
try:
IP_adress=tr.find('td').get_text()
IP_port=tr.find('td',attrs={'data-title':"PORT"}).get_text()
IP="http://"+IP_adress+":"+IP_port
proxies={'http':IP}
#print(proxies)
try:
response = requests.get('http://www.baidu.com', proxies=proxies,timeout=6)#########
r.lpush('IP',IP)
print("可yong+1"+IP)
except :
print("false")
except Exception:
pass
else:
print('********************被墙*************************')
然后我写了一个test.py文件用来检测redis中的IP是否可用,代码如下:
#用来测试代理池里面代理IP是否可用
import redis
import requests
import time
class test:
def test_IP(r):# 从列表的尾部取出一个ip
while r.llen('IP') >12 :
try:
ip=str(r.rpop('IP'),encoding='utf-8')# redis导出的数据都是bytes类型的,所以我们必须将其str化,必须加enconding参数
proxies = {'http': ip}# 测试ip有没有用
try:
html=requests.get("http://www.baidu.com",proxies=proxies,timeout=6)
if html.status_code == 200:
r.lpush('IP',ip)
print('valid IP')
except :
print('丢弃无用的ip')
time.sleep(3)
except :
print("IP池枯竭")
#time.sleep(20)
然后就写了一个run.py来运行这个代理池,代码如下:
from crawl_IP import crawl
import redis
import time
from tester import test
if __name__ == '__main__':
count_1=16
count_2=17
R =redis.Redis(host='localhost',port=6379,db=2,password="")
while 1 :
while R.llen('IP') < 15 :
for i in range(count_1,count_2):
crawl.page_kuai(i,R)
time.sleep(2)
count_1=count_2
count_2+=1
test.test_IP(R)
最后写了一个接口文件api.py来暴露IP,值得注意的是在我另外一篇文章里写过关于api.py运行的问题https://mp.csdn.net/postedit/88383011,代码如下:
# coding:utf-8
# 用于做接口,使其他的程序能够获得这个程序的开发出来的有用的IP
from flask import Flask
import redis
__all__ = ['app']
app = Flask(__name__)
@app.route('/')
def get_proxy():
R =redis.Redis(host='localhost',port=6379,db=2,password="")
ip=R.rpop('IP')
R.lpush('IP',ip)
return ip
app.run() # 当你运行这段代码时,在浏览器中输入localhost:5000,就会出现ip
源码在我github里:https://github.com/coder23263/IP_Proxy,谢谢观看,如有疑问欢迎留言。