轉:https://blog.csdn.net/weixin_42480489/article/details/83447494
網上不少文章關于代理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無效!")
? ? ------------------------
? ? 附:關鍵代碼在jupyter notebook中測試結果如下圖
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
