python代理池删除删除失效ip_python代理池的构建2——代理ip是否可用的处理和检查...

#-*-coding:utf-8-*-#check ip

'''目标:检查代理IP速度,匿名程度以及支持的协议类型.

步骤:

检查代理IP速度和匿名程度;

代理IP速度:就是从发送请求到获取响应的时间间隔

匿名程度检查:

对http://httpbin.org/get 或https://httpbin.org/get 发送请求

如果响应的origin 中有',分割的两个IP就是透明代理IP

如果响应的headers 中包含Proxy-Connection 说明是匿名代理IP,否则就是高匿代理IP检查代理IP协议类型

如果http://httpbin. org/get 发送请求可以成功,说明支持http协议

如果https://httpbin. org/get 发送请求可以成功,说明支持https协议'''

importtimeimportrequestsimportsysimportjson

sys.path.append("..") #这一部分就是告诉你你要导入的模块在什么位置(相对于本模块地址)

sys.path.append("../..")from utils.http importget_requests_headersfrom settings importTEST_TIMEOUTfrom utils.log importloggerfrom domain importProxydefcheck_proxy(proxy):

proxies= { #分别对着一个代理ip,进行http尝试和https尝试

'http':'http://{}:{}'.format(proxy.ip,proxy.port),'https': 'https://{}:{}'.format(proxy.ip, proxy.port),

}

http,http_nick_type,http_speed= __check_http_proxies(proxies)

https, https_nick_type, https_speed= __check_http_proxies(proxies,False)#0->http,1->https,2->http and https

if http and https: #按之前的逻辑进行判断

proxy.protocol=2proxy.nick_type=http_nick_type

proxy.speed=http_speedelifhttp:

proxy.protocol=0

proxy.nick_type=http_nick_type

proxy.speed=http_speedelifhttps:

proxy.protocol= 1proxy.nick_type=https_nick_type

proxy.speed=https_speedreturnproxydef __check_http_proxies(proxies,is_http=True): #检查代理可用不

nick_type=-1speed=-1

ifis_http:

test_url= 'http://httpbin.org/get'

else:

test_url= 'https://httpbin.org/get'

try: #加上try,防止requests没访问到程序直接中断

start = time.time() #这个是记录当前时间

response = requests.get(test_url,headers=get_requests_headers(),proxies=proxies,timeout=TEST_TIMEOUT)#print(response.text)

ifresponse.ok:#ip speed

speed = round(time.time()-start)

dic= json.loads(response.text) #把返回信息转化成json类型,也就是字典类型

#ip origin

origin = dic['origin']

proxy_connection= dic['headers'].get('Proxy-Connection',None)#这里用get的原因是,如果获取不到内容可以赋值为None,而不会报错

if ',' inorigin:

nick_type=2

elifproxy_connection:

nick_type=1

else:

nick_type=0returnTrue,nick_type,speedelse:returnFalse,nick_type,speedexceptException as ex:#logger.exception(ex)

returnFalse,nick_type,speedif __name__ == '__main__': #程序测试

proxy = Proxy('117.95.55.40',port='9999')print(check_proxy(proxy))

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值