本篇文章小编给大家分享一下Python快速验证代理IP是否有效代码实现方法,文章代码介绍的很详细,小编觉得挺不错的,现在分享给大家供大家参考,有需要的小伙伴们可以来看看。
有时候,我们需要用到代理IP,比如在爬虫的时候,但是得到了IP之后,可能不知道怎么验证这些IP是不是有效的,这时候我们可以使用Python携带该IP来模拟访问某一个网站,如果多次未成功访问,则说明这个代理是无效的。
代码如下:
import requests import random import time http_ip = [ '118.163.13.200:8080', '222.223.182.66:8000', '51.158.186.242:8811', '171.37.79.129:9797', '139.255.123.194:4550' ] for i in range(10): try: ip_proxy = random.choice(http_ip) proxy_ip = { 'http': ip_proxy, 'https': ip_proxy, } print('使用代理的IP:', proxy_ip) response = requests.get("http://httpbin.org/ip", proxies=proxy_ip).text print(response) print('当前IP有效') time.sleep(2) except Exception as e: print(e.args[0]) print('当前IP无效') continue
运行结果如下:
使用代理的IP: {'http': '118.163.13.200:8080', 'https': '118.163.13.200:8080'}
HTTPConnectionPool(host='118.163.13.200', port=8080): Max retries exceeded with url:http://httpbin.org/ip(Caused by ProxyError('Cannot connect to proxy.', NewConnectionError('
当前IP无效
使用代理的IP: {'http': '51.158.186.242:8811', 'https': '51.158.186.242:8811'}
{
"origin": "51.158.186.242"
}
当前IP有效
使用代理的IP: {'http': '222.223.182.66:8000', 'https': '222.223.182.66:8000'}
{
"origin": "139.202.62.84, 222.223.182.66"
}
当前IP有效
使用代理的IP: {'http': '51.158.186.242:8811', 'https': '51.158.186.242:8811'}
{
"origin": "51.158.186.242"
}
当前IP有效
使用代理的IP: {'http': '51.158.186.242:8811', 'https': '51.158.186.242:8811'}
{
"origin": "51.158.186.242"
}
当前IP有效
使用代理的IP: {'http': '222.223.182.66:8000', 'https': '222.223.182.66:8000'}
HTTPConnectionPool(host='222.223.182.66', port=8000): Max retries exceeded with url:http://httpbin.org/ip(Caused by ProxyError('Cannot connect to proxy.', NewConnectionError('
当前IP无效
使用代理的IP: {'http': '139.255.123.194:4550', 'https': '139.255.123.194:4550'}
HTTPConnectionPool(host='139.255.123.194', port=4550): Max retries exceeded with url:http://httpbin.org/ip(Caused by ProxyError('Cannot connect to proxy.', NewConnectionError('
当前IP无效
使用代理的IP: {'http': '51.158.186.242:8811', 'https': '51.158.186.242:8811'}
{
"origin": "51.158.186.242"
}
当前IP有效
使用代理的IP: {'http': '51.158.186.242:8811', 'https': '51.158.186.242:8811'}
{
"origin": "51.158.186.242"
}
当前IP有效
使用代理的IP: {'http': '222.223.182.66:8000', 'https': '222.223.182.66:8000'}
HTTPConnectionPool(host='222.223.182.66', port=8000): Max retries exceeded with url:http://httpbin.org/ip(Caused by ProxyError('Cannot connect to proxy.', NewConnectionError('
当前IP无效
茶杯头甜蜜终章dlc 官方手机版v1.0.0.3
下载火柴人传说暗影格斗内置菜单 最新版v3.0.1
下载荒野乱斗测试服 安卓版v61.10.3
下载荒野乱斗彩虹服 安卓版v61.10.3
下载寒霜启示录 安卓版v1.25.10
寒霜启示录是一款生存模拟游戏,不少玩家可能对于末日都有着自己
末日城堡免广告版 安卓最新版v0.7.1
末日城堡免广告版是一款非常好玩的模拟经营类游戏,内部可以不看
甜蜜人生模拟器 最新版v1.4.5
甜蜜人生模拟器是一款非常好玩的模拟恋爱手游,玩家在这里能够对
武器锻造师内置功能菜单 v10.4
武器锻造师内置菜单版是游戏的破解版本,在该版本中为玩家提供了
开放空间overfield 安卓版v1.0.5
开放空间Overfield是一款箱庭养成经营手游,让你在广阔