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: (caused by proxyerror('cannot connect to proxy.', newconnectionerror('<urllib3.connection.httpconnection object at 0x00000247674f5f88>: failed to establish a new connection: [winerror 10060] 由于连接方在一段时间后没有正确答复或连接的主机没有反应,连接尝试失败。')))
当前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: (caused by proxyerror('cannot connect to proxy.', newconnectionerror('<urllib3.connection.httpconnection object at 0x00000247675067c8>: failed to establish a new connection: [winerror 10060] 由于连接方在一段时间后没有正确答复或连接的主机没有反应,连接尝试失败。')))
当前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: (caused by proxyerror('cannot connect to proxy.', newconnectionerror('<urllib3.connection.httpconnection object at 0x00000247674f55c8>: failed to establish a new connection: [winerror 10060] 由于连接方在一段时间后没有正确答复或连接的主机没有反应,连接尝试失败。')))
当前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: (caused by proxyerror('cannot connect to proxy.', newconnectionerror('<urllib3.connection.httpconnection object at 0x0000024767514908>: failed to establish a new connection: [winerror 10060] 由于连接方在一段时间后没有正确答复或连接的主机没有反应,连接尝试失败。')))
当前ip无效
到此这篇关于python 快速验证代理ip是否有效的方法实现的文章就介绍到这了,更多相关python 验证代理ip是否有效内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!