IPRoyal Python 輪換 IP

IPRoyal 住宅 IP 池有 2000 萬+ IP,關鍵是怎麼用。粘性(Sticky)一個 IP 用 30 分鐘適合賬號登入場景,輪換(Rotating)每次請求換 IP 適合爬蟲、批次註冊、反風控。本文用 Python 實現輪換 + 重試的完整方案。

兩種模式區別

模式IP 切換頻率適用場景
Sticky每 10/30 分鐘換一次賬號登入、API 呼叫、量化持續會話
Rotating每次請求隨機換爬蟲、批次註冊、反風控

IPRoyal 後臺可以生成兩種模式的代理憑證。

Rotating 代理憑證格式

登入 IPRoyal Dashboard → Residential → Generate → 選 Rotating → 拿到:

Proxy: gw.iproyal.com
Port: 12321
Username: YOUR_USER
Password: YOUR_PASS_country-us_session-rotate

session-rotate 是關鍵:每次發請求都會從池子裡抓新 IP。

Python 基礎用法

import requests

proxy_url = "http://USER:[email protected]:12321"
proxies = {"http": proxy_url, "https": proxy_url}

for i in range(5):
    r = requests.get("https://ipinfo.io/json", proxies=proxies, timeout=10)
    print(f"Request {i+1}: {r.json()['ip']} ({r.json().get('city')})")

預期輸出:

Request 1: 142.176.xx.xx (San Diego)
Request 2: 71.192.xx.xx (New York)
Request 3: 98.44.xx.xx (Austin)
Request 4: 24.128.xx.xx (Boston)
Request 5: 104.128.xx.xx (Chicago)

每次請求都是不同的住宅 IP,像不同地方的普通家庭使用者在訪問。

實戰 1:爬蟲反封禁

爬大型網站(如亞馬遜商品價、Google 搜尋結果)時經常被 ban。輪換 IP 讓目標網站認為你是"很多不同使用者"而不是機器人。

import requests
import time
from urllib.parse import quote

proxy = "http://USER:[email protected]:12321"
PROXIES = {"http": proxy, "https": proxy}

def scrape_url(url, max_retries=3):
    """每次失敗自動換 IP 重試"""
    for attempt in range(max_retries):
        try:
            # session-rotate 保證每次重試都是新 IP
            r = requests.get(url, proxies=PROXIES, timeout=15,
                             headers={"User-Agent": "Mozilla/5.0 ..."})
            if r.status_code == 200:
                return r.text
            elif r.status_code in (403, 429, 503):
                print(f"  被 ban ({r.status_code}),換 IP 重試 [{attempt+1}]")
                time.sleep(2)
                continue
            else:
                print(f"  HTTP {r.status_code}")
                return None
        except requests.Timeout:
            print(f"  超時,重試 [{attempt+1}]")
            time.sleep(3)
        except requests.RequestException as e:
            print(f"  error: {e}")
            time.sleep(2)
    return None

# 示例:爬 100 個 URL
urls = [f"https://example.com/product/{i}" for i in range(100)]
for u in urls:
    html = scrape_url(u)
    if html: process(html)  # 你的解析邏輯
    time.sleep(0.5)  # 溫和一點

關鍵:session-rotate 讓每次 requests.get() 都用新 IP,所以被 ban 的請求重試時自動換 IP,不需要手動切換。

實戰 2:繞過地區限制

某些網站只對特定地區開放。IPRoyal 支援指定國家:

# 美國 IP
us_proxy = "http://USER:[email protected]:12321"

# 日本 IP
jp_proxy = "http://USER:[email protected]:12321"

# 英國 IP
uk_proxy = "http://USER:[email protected]:12321"

def get_by_country(url, country="us"):
    proxy_url = f"http://USER:PASS_country-{country}[email protected]:12321"
    return requests.get(url, proxies={"http": proxy_url, "https": proxy_url}).text

# 爬 Netflix 美國和日本的不同內容
html_us = get_by_country("https://netflix.com/browse", "us")
html_jp = get_by_country("https://netflix.com/browse", "jp")

實戰 3:批次賬號註冊

(法律注意:請確保目標網站 ToS 允許。常見合規場景:同人郵箱註冊多個正當業務賬號,或測試用途)

import random

def register_account(email, password, country="us"):
    proxy_url = f"http://USER:PASS_country-{country}[email protected]:12321"
    PROXIES = {"http": proxy_url, "https": proxy_url}
    
    # 模擬真人行為:隨機延遲
    time.sleep(random.uniform(2, 5))
    
    # 訪問註冊頁先(獲取 CSRF token)
    session = requests.Session()
    session.proxies = PROXIES
    session.headers["User-Agent"] = random_user_agent()
    
    resp = session.get("https://target.com/register")
    csrf = extract_csrf(resp.text)
    
    time.sleep(random.uniform(3, 8))  # 模擬"填寫表單"時間
    
    resp = session.post("https://target.com/register", data={
        "email": email,
        "password": password,
        "_csrf": csrf,
    })
    return resp.status_code == 200

# 批次
emails = load_emails()
for email in emails:
    success = register_account(email, "StrongPass123!", random.choice(["us", "gb", "ca"]))
    print(f"{email}: {'✓' if success else '✗'}")
    time.sleep(random.uniform(30, 120))  # 賬號間足夠間隔

實戰 4:量化策略的請求分散

Binance 對單個 IP 有 rate limit(每分鐘請求數)。如果量化策略頻繁呼叫,輪換 IP 能繞開這個限制:

import random

PROXY_POOL = [
    f"http://USER:[email protected]:12321",
    f"http://USER:[email protected]:12321",
    f"http://USER:[email protected]:12321",
]

def binance_request(path):
    """分散請求到不同地區的住宅 IP"""
    proxy = random.choice(PROXY_POOL)
    return requests.get(f"https://api.binance.com{path}",
                        proxies={"https": proxy}, timeout=5)

# 併發用這個函式,每次請求都是新地區的新 IP

失敗重試的更好姿勢(用 tenacity)

手寫重試容易漏情況。用 tenacity 庫:

from tenacity import retry, stop_after_attempt, wait_exponential

@retry(stop=stop_after_attempt(5), wait=wait_exponential(multiplier=1, min=2, max=30))
def scrape_with_retry(url):
    r = requests.get(url, proxies=PROXIES, timeout=15)
    r.raise_for_status()  # 4xx/5xx 拋異常觸發重試
    return r.text

自動指數回退(2s, 4s, 8s, 16s, 30s),且 session-rotate 保證每次都是新 IP。

費用對比

方案月成本(10GB 流量)穩定性IP 質量
IPRoyal Residential Rotating$70⭐⭐⭐⭐⭐家庭寬頻
Bright Data$300⭐⭐⭐⭐⭐同上但更貴
免費代理列表$0⭐95% 不可用
VPS 自建$20-50⭐⭐⭐機房 IP,易封

IPRoyal 是價效比最高的,但貴在流量消耗(按 GB 付費)。爬大圖/影片的場景流量消耗快,要算清楚。

總結

IPRoyal Rotating 模式解決:

  • 爬蟲反封禁
  • 地區限制繞過
  • 批次操作
  • API rate limit 分散

Python 配合 session-rotate 字尾實現自動換 IP。失敗重試用 tenacity 更優雅。

想開始: → IPRoyal 按流量付費,預充 $5 就能用(2000 萬+ 住宅 IP 池)

注意事項:

  • 遵守目標網站 ToS
  • 爬蟲加合理延遲,別把對方伺服器 DDoS 了
  • 資料保密(IPRoyal 看得到你的請求 URL 但看不到內容,HTTPS 加密)

延伸閱讀: