使用提示
1.基於requests的代碼樣例支持訪問http,https網頁,推薦使用
2.requests不是python原生庫,需要安裝才能使用: pip install requests
-
#!/usr/bin/env python
-
# -*- coding: utf-8 -*-
-
"""
-
使用requests請求代理服務器
-
請求http和https網頁均適用
-
"""
-
import requests
# 提取代理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 = requests.get(api_url).text
-
# 用戶名密碼認證(私密代理/獨享代理)
-
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發送請求
-
response = requests.get(target_url, proxies=proxies)
-
# 獲取頁面內容
-
if response.status_code == 200:
-
print(response.text)