通过Python利用ADSL服务器和tinyproxy构建数据自己的动态代理IP池,用django+redis做web服务 (优化版)

代理池初始版:https://blog.csdn.net/MeteorCountry/article/details/82085238

上一篇文章中所搭建的代理池在使用过程中出现了点小问题,代理池中莫名的多出了一些无效代理,检查日志后返现是在更新代理

池时旧的代理IP没有删除成功,就添加了新的代理IP。究其原因是因为在请求删除接口时网络已断开导致多次请求失败,跳过了

删除这一步骤,进行了重拨、更新,于是对 ADSL 服务器端的代码进行了修改,又增加了日志功能,代码如下:

#!/usr/bin/python3
import re,time,os,requests,json,datetime,random

only = 'only1'
log_list = []

#获取时间
def getTime():
    numtime = datetime.datetime.now().strftime('%Y-%m-%d %H-%M-%S---')
    return numtime

#写入日志
def write_log():
    with open('proxy.log','a') as f:
        for i in log_list:
            f.write(i+'\n')
        f.write('\n')
        f.close()

#切换IP,重启代理服务
def changeIP():
    os.system('pppoe-stop')
    time.sleep(4)
    os.popen('service tinyproxy stop')
    os.popen('pppoe-start')
    time.sleep(7)
    os.popen('service tinyproxy start')

#取出当前IP
def extractIP():
    infor = os.popen('pppoe-status').read()
    try:
        ip = re.search('(\d+\.\d+\.\d+\.\d+)',infor).group(1)
        return ip
    except Exception as e:
        log_list.append(getTime()+'提取IP错误:'+str(e))
        return False

def updateDel():
    url = 'http://*.*.*.*:8000/proxy/updateDel?&only={0}'.format(only)
    #是否删除成功
    state = False
    for i in range(2):
        try:
            res = requests.get(url,timeout=3)
            infor = json.loads(res.text)
            if infor['state']:
                log_list.append(getTime() + '删除旧IP成功')
                state = True
                break
            else:
                log_list.append(getTime() + '删除IP失败')
        except Exception as e:
            log_list.append(getTime() + '删除IP失败:'+str(e))
            continue
    return state

def updatePut(ip):
    ip = ip+':'+'8888'
    url = 'http://*.*.*.*:8000/proxy/updatePut?ip={0}&only={1}'.format(ip,only)
    for i in range(3):
        try:
            res = requests.get(url,timeout=3)
            infor = json.loads(res.text)
            if infor['state']:
                break
            else:
                log_list.append(getTime() + '更新IP失败')
        except Exception as e:
            log_list.append(getTime() + '更新IP失败'+str(e))
            continue

if __name__ == '__main__':
    a = 1
    while True:
        if a==2:
            time.sleep(random.randrange(45,70))
        a=2
        state = updateDel()
        time.sleep(2)
        while True:
            #重新连接
            changeIP()
            #取出当前IP
            ip = extractIP()
            if ip:
                break
        #请求代理池中旧IP失败,此处重新请求删除接口
        if not state:
            log_list.append(getTime() + '第二次执行删除旧IP方法')
            updateDel()
        updatePut(ip)
        log_list.append(getTime()+'已经更新IP:{0}'.format(ip))
        write_log()
        log_list = []

截止到现在,新的代理池用了三台 ADSL 服务器(每台服务器每分钟提供一个代理IP,每个IP可以支持20个并发对请求速度无影响),已使用一星期,再无异常。

本文原创,如需转载请注明来源。

注 : 网络爬虫要尽量减小对被爬取网站影响, 如在被爬取网站每天访问量较小的时间段去爬取,一切为了和平发展。

猜你喜欢

转载自blog.csdn.net/MeteorCountry/article/details/82729027