当前位置: 首页 > 后端技术 > Python

Python快速验证代理IP是否有效

时间:2023-03-26 14:07:10 Python

有时候,我们需要用到代理IP,比如爬虫的时候,但是获取到IP后,我们可能不知道如何验证这些IP是否有效。这时候我们可以使用PythonBring这个IP来模拟访问某个网站。如果多次访问失败,说明代理失效。代码如下:importrequestimportrandomimporttimehttp_ip=['118.163.13.200:8080','222.223.182.66:8000','51.158.186.242:8811','171.37.79.129:9797','139.254.1255']foriinrange(10):try:ip_proxy=random.choice(http_ip)proxy_ip={'http':ip_proxy,'https':ip_proxy,}print('IPusingproxy:',proxy_ip)response=requests.get("http://httpbin.org/ip",proxies=proxy_ip).textprint(response)print('当前IP有效')time.sleep(2)exceptexceptase: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):最大重试次数超过url:http://httpbin.org/ip(由ProxyError('无法连接到代理。',NewConnectionError(':newconnection:[WinError10060]连接尝试失败,因为连接方在一段时间后没有正确回复或连接的主机被我反应迟钝。')))当前IP无效代理IP:{'http':'51.158.186.242:8811','https':'51.158.186.242:8811'}{"origin":"51.158.186.242"}当前IP有效外汇代理http://www.fx61.com/ib.html使用代理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):Maxretriesexceededwithurl:http://httpbin.org/ip(CausedbyProxyError('Cannotconnecttoproxy.',NewConnectionError(':Failedtoestablishanewconnection:[WinError10060]因为连接方在一段时间后没有正确回复时间或连接主机无响应且连接尝试失败。')))当前IP无效代理IP:{'http':'139.255.123.194:4550','https':'139.255.123.194:4550'}HTTPConnectionPool(host='139.255.123.194',port=4550):最大重试次数超过url:http://httpbin.org/ip(由ProxyError('无法连接到代理。',NewConnectionError(':无法建立新连接:[WinError10060]时间后没有正确回复或连接主机无响应,连接尝试失败。')))当前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):最大重试次数超过url:http://httpbin.org/ip(由ProxyError('无法连接到代理。',NewConnectionError(':Failed建立新连接:[WinError10060]由于连接方在一段时间后没有正确回复或连接的主机没有响应,连接尝试失败。')))当前IP无效