Python3使用urllib调用Http代理IP的代码样例

温馨提示:
1. urllib的代码样例同时支持访问http和https网页
2. 运行环境要求 python3.x
3. 建议全局取消证书验证避免访问https网页报错
4. 代码样例中的代理IP和端口均为虚构,请通过ipip9的API提取链接获取代理IP后使用,避免报错



参考样例

import urllib.request
import ssl

# 全局取消证书验证避免访问https网页报错
ssl._create_default_https_context = ssl._create_unverified_context

# 用户名密码授权
username="username"
password="password"
proxies={
	"http":"http://username:[email protected]:12345,
	"https":http://username:[email protected]:12345
}

# 终端IP授权(需提前绑定终端IP)
#proxies={
#	"http":"http://168.168.168.168:12345",
#	"https":"http://168.168.168.168:12345"
 #}

# 要访问的目标网页
target_url="https://example.com"

# 使用代理IP发送请求
proxy_support=urllib.request.ProxyHandler(proxies)
opener = urllib.request.build_opener(proxy_support)
urllib.request.install_opener(opener)
response=urllib.request.urlopen(target_url)

# 获取页面内容
if response.code==200:
	print(response.read().decode('utf-8'))