Налаштування проксі в Python
Підключіть SotaProxy до будь-якої Python HTTP-бібліотеки менш ніж за 5 хвилин.
Python - найпоширеніша мова для вебскрапінгу та автоматизації. SotaProxy працює з кожною основною Python HTTP-бібліотекою: requests, httpx, aiohttp і urllib. Конфігурація однакова в усіх - задайте URL проксі з вашими обліковими даними.
Посібник із налаштування
Встановіть requests (якщо потрібно)
pip install requestsБібліотека requests - найпростіший варіант для синхронного скрапінгу.
Базове налаштування проксі
import requests
proxy_url = "http://YOUR_USERNAME:YOUR_PASSWORD@proxy.sotaproxy.com:10000"
proxies = {
"http": proxy_url,
"https": proxy_url,
}
response = requests.get("https://httpbin.org/ip", proxies=proxies)
print(response.json())Замініть YOUR_USERNAME і YOUR_PASSWORD на ваші облікові дані SotaProxy. Формат URL проксі - http://user:pass@host:port.
Sticky-сесія (один IP для кількох запитів)
import requests
# Append session ID to username for sticky sessions
session_id = 1001
proxy_url = f"http://YOUR_USERNAME_s_{session_id}_ttl_15m:YOUR_PASSWORD@proxy.sotaproxy.com:10000"
proxies = {"http": proxy_url, "https": proxy_url}
# Both requests will use the same IP
r1 = requests.get("https://example.com/page1", proxies=proxies)
r2 = requests.get("https://example.com/page2", proxies=proxies)Додайте _s_{id}_ttl_15m до імені користувача, щоб тримати один IP на кількох запитах. Змініть ID сесії, щоб ротувати на новий IP.
Гео-таргетинг
import requests
# Target a specific country (US in this example)
proxy_url = "http://YOUR_USERNAME_c_US:YOUR_PASSWORD@proxy.sotaproxy.com:10000"
proxies = {"http": proxy_url, "https": proxy_url}
response = requests.get("https://example.com", proxies=proxies)Додайте _c_XX до імені користувача, де XX це ISO-код країни великими літерами: US, DE, GB, FR.
Повний приклад
Асинхронний скрапер з httpx і ротацією проксі
import httpx
import asyncio
PROXY_URL = "http://YOUR_USERNAME:YOUR_PASSWORD@proxy.sotaproxy.com:10000"
URLS = [
"https://example.com/product/1",
"https://example.com/product/2",
"https://example.com/product/3",
]
async def fetch(client, url):
try:
response = await client.get(url, timeout=30.0)
return {"url": url, "status": response.status_code, "length": len(response.text)}
except Exception as e:
return {"url": url, "error": str(e)}
async def main():
async with httpx.AsyncClient(proxy=PROXY_URL) as client:
tasks = [fetch(client, url) for url in URLS]
results = await asyncio.gather(*tasks)
for result in results:
print(result)
asyncio.run(main())Автоматизуй через SotaProxy API
Усе описане вище працює без відкриття дашборда. З API-ключем Python може отримувати свіжі дані проксі, купувати нові та продовжувати ті, що спливають, - прямо з коду.
import requests
API = "https://api.sotaproxy.com/api/v1"
H = {"Authorization": "Bearer sk_live_your_key"}
# Every active proxy on your account - no copy-pasting credentials
proxies = requests.get(f"{API}/proxies", headers=H).json()["proxies"]
p = proxies[0]
proxy_url = f"http://{p['login']}:{p['password']}@{p['ip']}:{p['portHttp']}"
# Buy more when you scale (price-check first with POST /quote)
requests.post(
f"{API}/orders",
headers={**H, "Idempotency-Key": "my-unique-order-id"},
json={"product": "ipv4", "countryId": 565, "periodId": "1m", "quantity": 5},
)Both address types in one client
Our residential pool and our static addresses authenticate the same way, by login and password. The difference lives in the host and in what you put after the login:
SOCKS5 needs an extra package. Run pip install requests[socks] first, then use socks5h:// so that DNS resolves on our side rather than on yours.
Rotating without a rotation library
You do not need middleware to change addresses. Rotating residential gives you a new IP on every request by default, and a session id pins one when you need it to hold:
Python: a session per worker, rotation everywhere else
import requests
BASE = "proxy.sotaproxy.com:10000"
USER, PWD = "login", "password"
def proxy(country=None, session=None, ttl="15m"):
login = USER
if country:
login += f"_c_{country}"
if session:
login += f"_s_{session}_ttl_{ttl}"
url = f"http://{login}:{PWD}@{BASE}"
return {"http": url, "https": url}
# new IP per request
requests.get(url, proxies=proxy(), timeout=30)
# same IP for a multi-step flow
s = requests.Session()
s.proxies.update(proxy(country="US", session=7))
s.get(login_url); s.post(login_url, data=creds)- Reuse a Session object per worker. It keeps the connection to our endpoint alive and cuts the handshake from every request.
- Set timeout on every call. Without it requests waits forever, and a stalled residential route will hang a worker for the rest of the run.
- Send Accept-Encoding: gzip. Residential is billed per gigabyte and an HTML page compresses three to four times.
- Do not put credentials in HTTP_PROXY environment variables on shared machines. Every subprocess inherits them.
What breaks in requests specifically
socks5:// leaks your DNS
With socks5:// the hostname is resolved locally, so your resolver sees every target. Use socks5h:// and the lookup happens through the proxy.
verify=False hides real failures
People disable certificate checks to silence an error that was actually a 407 in disguise. Fix the credentials instead.
One Session shared across threads
requests.Session is not thread-safe. Give each thread its own, or connections cross and responses arrive on the wrong caller.
Retrying without changing the address
A 429 means that address is done for now. Retry through a new one rather than the same login.
Нотатки та поради
- •Перевірте зв’язок із проксі: curl -x http://user:pass@proxy.sotaproxy.com:10000 https://httpbin.org/ip
- •За проблем із перевіркою SSL задайте verify=False у requests (не рекомендується для продакшену) або додайте CA-сертифікат проксі.
- •Налаштування проксі в aiohttp використовує connector=aiohttp.TCPConnector() і proxy=proxy_url у session.get().
FAQ
Як використовувати ротаційні проксі з Python requests?
Задайте словник proxies з вашим ендпоінтом SotaProxy один раз. Ротація відбувається на боці сервера - міняти URL проксі між запитами не потрібно.
Чи працює SotaProxy зі Scrapy?
Так. Задайте DOWNLOADER_MIDDLEWARES і HTTP_PROXY у settings.py або використовуйте пакет middleware для ротації проксі.
Як обробляти помилки автентифікації проксі?
Переконайтеся, що ім’я користувача й пароль в URL проксі URL-кодовані, якщо містять спецсимволи. Спершу протестуйте через curl, щоб відокремити проблеми автентифікації від проблем коду.
Схожі інтеграції
Отримай облікові дані проксі
Зареєструйся, поповни баланс і скопіюй ендпоінт у Python. Займе менше 5 хвилин.
Почати