电子说
华益云HTTP代理API有效期是一年,也就是说一年内这1万IP用完就没了,如果你一年都用不完那到时候剩余IP才会被清零,对于调试代码来说时间充足灵活。
华益云还免费提供一些主流语言示例代码demo,可到帮助文档获取(python,java,php,c,go,易语言)
python代码中如何使用HTTP代理。
# 此版本无需安装依赖
import urllib
import urllib.request
import urllib
def main():
# 发送给服务器的标识
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,注册就白嫖1万IP)
proxyUrl = "http://http.9vps.com/getip.asp?username=166xxxx6597&pwd=xxxxbaa59ce237dff65134984b9cxxxx&geshi=1&fenge=1&fengefu=&Contenttype=1&getnum=20&setcity=&operate=all&";
# 请求代理url,获取代理ip
outPutProxy = getProxy(proxyUrl, userAgent)
if len(outPutProxy)==0:
# 没有获取到代理
return
# 目标请求网站
# https://httpbin.org/get
url = "https://www.qq.com/"
content = None
for _ in range(0, 3):
# 最多尝试三次
try:
# 从列表中取出一个代理出来
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):
# 如果发现没有代理了,就去获取下。
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!用户名或密码错误","success":false}
if "{" in proxyIps:
raise Exception("[错误]"+proxyIps)
outPutProxy = proxyIps.splitlines()
except Exception as e:
print(e)
print("总共获取了"+str(len(outPutProxy))+"个代理")
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:
# 没有代理走这个
request = urllib.request.Request(url, headers=headers)
response = urllib.request.urlopen(request, timeout=5)
#response = opener.open(request)
html = response.read()
# # 设置编码,防止乱码
# 手动设置网页字符编码方式
return html.decode("utf-8", "ignore")
main()
全部0条评论
快来发表一下你的评论吧 !