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的可以私聊我,量大从惠