python检测代理ip是否有效问题
作者:小胖_@
这篇文章主要介绍了python检测代理ip是否有效问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
python检测代理ip是否有效
测试环境
python3.6 、window10系统
测试方法
第一种
- 使用requests模块。
- 使用requests.get() 发请求,根据其返回的网页内容进行判断,代理ip是否有效。
import telnetlib
try:
telnetlib.Telnet(ip, port, timeout=3)
print("代理IP有效!")
except:
print("代理IP无效!")- 缺点:虽然可以检测代理ip是否有效,但是该方法只能用于检测少量的代理ip,原因是该方法检测速度比较慢,主要耗时的是发请求这一过程。(可以使用)
第二种
- telnet 方法。
import telnetlibtry: telnetlib.Telnet(ip, port, timeout=3) print("代理IP有效!")except: print("代理IP无效!")
缺点:虽然该方法可以比较快速的验证,但是经测试发现一些代理ip可以测试通过,但实际上代理ip仍然无效。(不推荐使用)
第三种
利用的http://icanhazip.com/返回的IP进行校验,如返回的是代理池的IP,说明代理有效,否则实际代理无效
def check_proxy(ip, port): """第二种:""" try: # 设置重连次数 requests.adapters.DEFAULT_RETRIES = 3 # IP = random.choice(IPAgents) proxy = f"http://{<!-- -->ip}:{<!-- -->port}" # thisIP = "".join(IP.split(":")[0:1]) # print(thisIP) res = requests.get(url="http://icanhazip.com/", timeout=2, proxies={<!-- -->"http": proxy}) proxyIP = res.text if (proxyIP == proxy): print("代理IP:'" + proxyIP + "'有效!") return True else: print("2代理IP无效!") return False except: print("1代理IP无效!") return Falsedef check_proxy(ip, port):
"""第二种:"""
try:
# 设置重连次数
requests.adapters.DEFAULT_RETRIES = 3
# IP = random.choice(IPAgents)
proxy = f"http://{ip}:{port}"
# thisIP = "".join(IP.split(":")[0:1])
# print(thisIP)
res = requests.get(url="http://icanhazip.com/", timeout=2, proxies={"http": proxy})
proxyIP = res.text
if (proxyIP == proxy):
print("代理IP:'" + proxyIP + "'有效!")
return True
else:
print("2代理IP无效!")
return False
except:
print("1代理IP无效!")
return False推荐使用。
python批量检测IP代理是否可用
首先,我们需要导入必要的库:
import requests import time
然后,我们可以定义一个函数来检测代理是否可用:
def check_proxy(proxy):
# 使用代理发起请求,如果返回状态码为200,说明代理可用
try:
# 这里替换为你要请求的目标网站
response = requests.get('http://www.baidu.com', proxies={"http": proxy, "https": proxy}, timeout=5)
if response.status_code == 200:
return True
except Exception:
pass
return False接下来,我们可以读取包含代理的文本文件,并将可用的代理写入另一个文件中:
# 读取代理列表
with open('proxies.txt', 'r') as f:
proxy_list = f.read().splitlines()
# 创建用于保存可用代理的列表
valid_proxies = []
# 遍历代理列表,检测代理是否可用
for proxy in proxy_list:
if check_proxy(proxy):
valid_proxies.append(proxy)
# 将可用代理写入文件
with open('valid_proxies.txt', 'w') as f:
for proxy in valid_proxies:
f.write(proxy + '\n')总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
