華益云HTTP代理API有效期是一年,也就是說(shuō)一年內(nèi)這1萬(wàn)IP用完就沒(méi)了,如果你一年都用不完那到時(shí)候剩余IP才會(huì)被清零,對(duì)于調(diào)試代碼來(lái)說(shuō)時(shí)間充足靈活。
華益云還免費(fèi)提供一些主流語(yǔ)言示例代碼demo,可到幫助文檔獲?。?a href="http://wenjunhu.com/tags/python/" target="_blank">python,java,php,c,go,易語(yǔ)言)
python代碼中如何使用HTTP代理。
# 此版本無(wú)需安裝依賴
import urllib
import urllib.request
import urllib
def main():
# 發(fā)送給服務(wù)器的標(biāo)識(shí)
userAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/532.36 (KHTML, like Gecko) Chrome/97.0.4692.99 Safari/537.36"
# 代理api(這里我推薦使用www.9vps.com華益云的HTTP代理API,注冊(cè)就白嫖1萬(wàn)IP)
proxyUrl = "http://http.9vps.com/getip.asp?username=166xxxx6597&pwd=xxxxbaa59ce237dff65134984b9cxxxx&geshi=1&fenge=1&fengefu=&Contenttype=1&getnum=20&setcity=&operate=all&";
# 請(qǐng)求代理url,獲取代理ip
outPutProxy = getProxy(proxyUrl, userAgent)
if len(outPutProxy)==0:
# 沒(méi)有獲取到代理
return
# 目標(biāo)請(qǐng)求網(wǎng)站
# https://httpbin.org/get
url = "https://www.qq.com/"
content = None
for _ in range(0, 3):
# 最多嘗試三次
try:
# 從列表中取出一個(gè)代理出來(lái)
proxy = outPutProxy.pop(0)
px = {
"http": proxy,
"https": proxy
}
content = requestGet(url, userAgent, px)
break
except Exception as e:
print(e)
if (len(outPutProxy) == 0):
# 如果發(fā)現(xiàn)沒(méi)有代理了,就去獲取下。
outPutProxy = getProxy(proxyUrl, userAgent)
print(content)
def getProxy(proxyUrl, userAgent):
proxyIps=""
outPutProxy = []
try:
proxyIps = requestGet(proxyUrl, userAgent, None)
print("(proxyIps)", proxyIps)
# {"code":3002,"data":[],"msg":"error!用戶名或密碼錯(cuò)誤","success":false}
if "{" in proxyIps:
raise Exception("[錯(cuò)誤]"+proxyIps)
outPutProxy = proxyIps.splitlines()
except Exception as e:
print(e)
print("總共獲取了"+str(len(outPutProxy))+"個(gè)代理")
return outPutProxy
def requestGet(url, userAgent, proxy):
headers = {
"User-Agent": userAgent
}
# httpproxy_handler = urllib.ProxyHandler({"http" : " 180.104.192.217:22036"})
response = None
if (proxy):
proxyHandler = urllib.request.ProxyHandler(proxy)
opener = urllib.request.build_opener(proxyHandler, urllib.request.HTTPHandler)
urllib.request.install_opener(opener)
request = urllib.request.Request(url, headers=headers)
response = urllib.request.urlopen(request, timeout=5)
else:
# 沒(méi)有代理走這個(gè)
request = urllib.request.Request(url, headers=headers)
response = urllib.request.urlopen(request, timeout=5)
#response = opener.open(request)
html = response.read()
# # 設(shè)置編碼,防止亂碼
# 手動(dòng)設(shè)置網(wǎng)頁(yè)字符編碼方式
return html.decode("utf-8", "ignore")
main()
-
HTTP
+關(guān)注
關(guān)注
0文章
505瀏覽量
31242 -
代碼
+關(guān)注
關(guān)注
30文章
4788瀏覽量
68628 -
python
+關(guān)注
關(guān)注
56文章
4797瀏覽量
84695
發(fā)布評(píng)論請(qǐng)先 登錄
相關(guān)推薦
評(píng)論