python中設置代理的方法
1、設置http和https代理
import requests
import time
from fake_useragent import UserAgent
if __name__ == '__main__':
# 客戶ip提取鏈接,每次提取1個,提取鏈接可以換成自己購買的
url = 'http://api.shenlongip.com/ip?key=7wcdfdbd&pattern=text&count=1&need=1000&protocol=1'
# 訪問的目標地址
targeturl = 'http://myip.ipip.net'
response = requests.get(url)
content = response.content.decode("utf-8").strip()
print('提取IP:' + content)
nowtime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
print('提取IP時間:' + nowtime)
sj = content.strip().split(":", 1)
sj1 = sj[0]
print("IP:", sj1)
sj2 = sj[1]
print("端口:", sj2)
try:
proxyMeta = "http://4cr9yf:ad675zh6@%(host)s:%(port)s" % { # 賬密驗證,需要購買的代理套餐開通才可使用賬密驗證,此種情況無需加白名單
# proxyMeta = "http://%(host)s:%(port)s" % {#白名單驗證
"host": sj1,
"port": sj2,
}
print("代理1:", proxyMeta)
proxysdata = {
'http': proxyMeta,
'https': proxyMeta
}
# 設置隨機ua
ua = UserAgent(verify_ssl=False)
headers = {
"user-agent": ua.random,
}
# print("請求頭信息:",ua.random)
start = int(round(time.time() * 1000))
resp = requests.get(targeturl, headers=headers, timeout=20, proxies=proxysdata)
costTime = int(round(time.time() * 1000)) - start
print("耗時:" + str(costTime) + "ms")
print("返回狀態:",resp.status_code)
except Exception as e:
print(e)
2、設置socks5代理
import requests
import time
# 請求地址
if __name__ == '__main__':
targetUrl = "http://myip.ipip.net"
proxyHost = "43.248.79.156"
proxyPort = "60949"
# #pip install -U requests[socks] socks5代理
#白名單驗證
# proxyMeta = "socks5://%(host)s:%(port)s" % {
#
# "host" : proxyHost,
#
# "port" : proxyPort,
#}
#賬號密碼驗證
proxyMeta = "socks5://4cr9yf:ad675zh6@%(host)s:%(port)s" % {
"host": proxyHost,
"port": proxyPort,
}
proxies = {
"http": proxyMeta,
"https": proxyMeta
}
start = int(round(time.time() * 1000))
resp = requests.get(targetUrl, proxies=proxies,timeout=25,allow_redirects=False)
costTime = int(round(time.time() * 1000)) - start
print("耗時:" + str(costTime) + "ms")
print (resp.text)
print("耗時:" + str(costTime) + "ms")
有需要國內、國內代理ip的可以私聊我,量大從惠