python中怎么使用HTTP代理。
以下代碼主要圍繞第一次接觸HTTP代理IP的python新手來(lái)寫(xiě)。(步驟注釋清晰)
直接把下面示例代碼中的HTTP代理API,替換成你后臺(tái)生成的代理API鏈接,就可以跑起來(lái)了。
以下是一個(gè)示例代碼,只是一個(gè)基礎(chǔ)的演示,具體的代碼還是要根據(jù)你業(yè)務(wù)的實(shí)際情況去寫(xiě)的。
示例代碼中的HTTP代理IP,我使用的是華益云的HTTP代理,注冊(cè)就白嫖1萬(wàn)個(gè)高匿爬蟲(chóng)IP,有效期是一年,對(duì)于調(diào)試代碼來(lái)說(shuō)這個(gè)時(shí)間是非常的友好。(步驟注釋清晰)
示例代碼demo中同款HTTP代理API-點(diǎn)我免費(fèi)領(lǐng)取10000個(gè)高匿IP
打開(kāi)代理API,獲取里面的IP,使用IP訪問(wèn)目標(biāo)網(wǎng)站,其實(shí)代碼中就是執(zhí)行這個(gè)過(guò)程而已,然后加了幾個(gè)錯(cuò)誤判斷有助于代碼的穩(wěn)定運(yùn)行。
# 此版本無(wú)需安裝依賴(lài)
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)論