Webshare API 接口使用完整教程
Webshare API 简介
Webshare 提供完整的 REST API,允许开发者通过代码动态管理代理IP,无需手动操作控制台。
主要功能:
- 获取代理IP列表
- 查询流量使用情况
- 设置 IP 白名单认证
- 管理子账号
获取 API Key
- 登录 Webshare 控制台
- 进入 API 页面
- 点击 Generate New Key 生成 API Key
- 复制保存(仅显示一次,请妥善保管)
API 基础信息
- Base URL:
https://proxy.webshare.io/api/v2/ - 认证方式: Token 认证(在 Header 中传递)
- 请求格式: JSON
headers = {
"Authorization": "Token your_api_key_here"
}
获取代理列表
GET /proxy/list/
import requests
API_KEY = "your_api_key"
response = requests.get(
"https://proxy.webshare.io/api/v2/proxy/list/",
headers={"Authorization": f"Token {API_KEY}"},
params={
"mode": "direct", # direct = 数据中心, residential = 住宅
"page": 1,
"page_size": 100, # 每页最多100条
"country_code__in": "US,GB", # 筛选国家
}
)
data = response.json()
print(f"总代理数: {data['count']}")
for proxy in data["results"]:
print(f"{proxy['proxy_address']}:{proxy['port']} | {proxy['username']}:{proxy['password']}")
响应字段说明
{
"count": 100,
"results": [
{
"id": "abc123",
"proxy_address": "1.2.3.4",
"port": 80,
"username": "user123",
"password": "pass456",
"country_code": "US",
"city_name": "New York",
"valid": true
}
]
}
查询流量使用情况
GET /subscription/
response = requests.get(
"https://proxy.webshare.io/api/v2/subscription/",
headers={"Authorization": f"Token {API_KEY}"}
)
sub = response.json()
bandwidth = sub["bandwidth"]
print(f"已用流量: {bandwidth['used'] / 1e9:.2f} GB")
print(f"总流量: {bandwidth['total'] / 1e9:.2f} GB")
print(f"剩余: {(bandwidth['total'] - bandwidth['used']) / 1e9:.2f} GB")
IP 白名单认证(无需用户名密码)
Webshare 支持将你的服务器 IP 加入白名单,之后使用代理无需输入用户名/密码:
POST /proxy/ipauthorization/
MY_SERVER_IP = "111.222.333.444" # 你的服务器公网IP
response = requests.post(
"https://proxy.webshare.io/api/v2/proxy/ipauthorization/",
headers={"Authorization": f"Token {API_KEY}"},
json={"ip_address": MY_SERVER_IP}
)
print(response.json())
加白名单后,使用代理时直接填写 代理IP:端口,不需要认证。
完整轮换代理示例
import requests
import random
class WebshareProxy:
def __init__(self, api_key):
self.api_key = api_key
self.proxies = []
self._load_proxies()
def _load_proxies(self):
resp = requests.get(
"https://proxy.webshare.io/api/v2/proxy/list/",
headers={"Authorization": f"Token {self.api_key}"},
params={"page_size": 100}
)
self.proxies = resp.json()["results"]
def get_proxy(self):
p = random.choice(self.proxies)
url = f"http://{p['username']}:{p['password']}@{p['proxy_address']}:{p['port']}"
return {"http": url, "https": url}
# 使用
ws = WebshareProxy("your_api_key")
for i in range(10):
proxy = ws.get_proxy()
r = requests.get("https://httpbin.org/ip", proxies=proxy, timeout=10)
print(f"请求 {i+1}: {r.json()['origin']}")
API 速率限制
Webshare API 有请求频率限制:
- 免费方案:60次/分钟
- 付费方案:300次/分钟
建议缓存代理列表,避免每次请求都调用 API。