使用提示
1.基於urllib的代碼樣例同時支持訪問http和https網頁
2.運行環境要求 python3.x
-
#!/usr/bin/env python
-
# -*- coding: utf-8 -*-
-
"""
-
使用urllib請求代理服務器
-
請求http和https網頁均適用
-
"""
-
import urllib.request
-
import ssl
# 全局取消證書驗證,避免訪問https網頁報錯
-
ssl._create_default_https_context = ssl._create_unverified_context
-
# 提取代理API接口,獲取1個代理IP
-
api_url = "http://dps.kdlapi.com/api/getdps/?orderid=9266892014xxxxx&signature=xxxxx&num=1&pt=1&sep=1"
-
# 獲取API接口返回的IP
-
proxy_ip = urllib.request.urlopen(api_url).read().decode("utf-8")
-
# 用戶名密碼認證(私密代理/獨享代理)
-
username = "username"
-
password = "password"
-
proxies = {
-
"http": "http://%(user)s:%(pwd)s@%(proxy)s/" % {"user": username, "pwd": password, "proxy": proxy_ip},
-
"https": "http://%(user)s:%(pwd)s@%(proxy)s/" % {"user": username, "pwd": password, "proxy": proxy_ip}
}
-
# 白名單方式(需提前設置白名單)
-
# proxies = {
-
# "http": "http://%(proxy)s/" % {"proxy": proxy_ip},
-
# "https": "http://%(proxy)s/" % {"proxy": proxy_ip}
-
# }
-
# 要訪問的目標網頁
-
target_url = "https://dev.kdlapi.com/testproxy"
-
# 使用代理IP發送請求
-
proxy_support = urllib.request.ProxyHandler(proxies)
-
opener = urllib.request.build_opener(proxy_support)
-
# urllib.request.install_opener(opener) 注意此處是全局設置代理,如用這種寫法進程內之後的所有urllib請求都會使用代理
-
# response = urllib.request.urlopen(target_url)
-
response = opener.open(target_url)
# 獲取頁面內容
-
if response.code == 200:
-
print(response.read().decode("utf-8"))