python 代理ip验证_Python 快速验证代理IP是否有效,再也不用担心被封IP了!
有時候,我們需要用到代理IP,比如在爬蟲的時候,但是得到了IP之后,可能不知道怎么驗證這些IP是不是有效的,這時候我們可以使用Python攜帶該IP來模擬訪問某一個網(wǎng)站,如果多次未成功訪問,則說明這個代理是無效的。
代碼如下:
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
運行結(jié)果如下:
使用代理的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:
當前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:
當前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:
當前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:
當前IP無效
總結(jié)
以上是生活随笔為你收集整理的python 代理ip验证_Python 快速验证代理IP是否有效,再也不用担心被封IP了!的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python输出word内容_Djang
- 下一篇: 二叉树的深度_[LeetCode 104