轉(zhuǎn):https://blog.csdn.net/weixin_42480489/article/details/83447494
網(wǎng)上不少文章關(guān)于代理IP的驗(yàn)證方法,例如
1.訪問百度網(wǎng)頁,依據(jù)其返回的網(wǎng)頁內(nèi)容進(jìn)行判斷
例如
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 + ':無效!!!')
經(jīng)測(cè)試,發(fā)現(xiàn)存在以下問題:
雖然代理無效,也會(huì)返回一個(gè)網(wǎng)頁,但不是百度,其內(nèi)容大于5000,因此存在bug。
2.telnet 方法
import telnetlib
try:
? ? telnetlib.Telnet(ip, port, timeout=2)
? ? ?? ?print("代理IP有效!")
except:
? ? ? ? print("代理IP無效!")
經(jīng)測(cè)試,發(fā)現(xiàn)存在以下問題:
雖然某些代理可以用telnet測(cè)試通過,但實(shí)際仍然上無效。有興趣的可在windows 終端中測(cè)試。
3.利用訪問http://icanhazip.com/返回的IP進(jìn)行測(cè)試,推薦使用
說明:利用的http://icanhazip.com/返回的IP進(jìn)行校驗(yàn),如返回的是代理池的IP,說明代理有效,否則實(shí)際代理無效
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無效!")
? ? ------------------------
? ? 附:關(guān)鍵代碼在jupyter notebook中測(cè)試結(jié)果如下圖
更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主
微信掃碼或搜索:z360901061

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