python:代理IP是否有效的测试方法

测试环境:ubantu18.04,python 3.6

网上不少文章关于代理IP的验证方法,例如
1.访问百度网页,依据其返回的网页内容进行判断
例如

import urllib.request
proxy=urllib.request.ProxyHandler({"http": "http://120.77.249.46:8080"})
opener=urllib.request.build_opener(proxy)
urllib.request.install_opener(opener)
data = urllib.request.urlopen('http://www.baidu.com',timeout = 2).read().decode('utf-8','ignore')
try:
    if(len(data) > 5000):
        print(thisIP + ':可用')
   else:
        print(thisIP + ':无效')
   except :
        print(thisIP + ':无效!!!')

经测试,发现存在以下问题:
虽然代理无效,也会返回一个网页,但不是百度,其内容大于5000,因此存在bug。

2.telnet 方法

import telnetlib
try:
    telnetlib.Telnet(ip, port, timeout=2)
    	print("代理IP有效!")
except:
        print("代理IP无效!")

经测试,发现存在以下问题:
虽然某些代理可以用telnet测试通过,但实际仍然上无效。有兴趣的可在windows 终端中测试。

3.利用访问http://icanhazip.com/返回的IP进行测试,推荐使用
说明:利用的http://icanhazip.com/返回的IP进行校验,如返回的是代理池的IP,说明代理有效,否则实际代理无效

import random
IPAgents = [
    "118.190.95.35:9001",
	]

try:
    requests.adapters.DEFAULT_RETRIES = 3
    IP = random.choice(IPAgents)
    thiProxy = "http://" + IP
    thisIP = "".join(IP.split(":")[0:1])
    #print(thisIP)
    res = requests.get(url="http://icanhazip.com/",timeout=8,proxies={"http":thisProxy})
    proxyIP = res.text
    if(proxyIP == thiProxy):
        print("代理IP:'"+ proxyIP + "'有效!")
    else:
        print("代理IP无效!")
except:
    print("代理IP无效!")

python:代理IP是否有效的测试方法