Configuración de proxy en Python
Conecta SotaProxy a cualquier librería HTTP de Python en menos de 5 minutos.
Python es el lenguaje más común para web scraping y automatización. SotaProxy funciona con todas las principales librerías HTTP de Python: requests, httpx, aiohttp y urllib. La configuración es la misma en todas - establece la URL del proxy con tus credenciales.
Guía de configuración
Instala requests (si hace falta)
pip install requestsLa librería requests es la opción más simple para scraping síncrono.
Configuración básica del proxy
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())Reemplaza YOUR_USERNAME y YOUR_PASSWORD por tus credenciales de SotaProxy. El formato de la URL del proxy es http://user:pass@host:port.
Sesión sticky (misma IP para varias solicitudes)
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)Añade _s_{id}_ttl_15m a tu nombre de usuario para mantener la misma IP en varias solicitudes. Cambia el ID de sesión para rotar a una IP nueva.
Geo-segmentación
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)Añade _c_XX a tu nombre de usuario, donde XX es el código de país ISO en mayúsculas: US, DE, GB, FR.
Ejemplo completo
Scraper asíncrono con httpx y rotación de proxy
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())Automatízalo con la API de SotaProxy
Todo lo anterior funciona sin abrir el panel. Con una clave API, Python puede obtener credenciales de proxy actualizadas, comprar nuevos proxies y renovar los que caducan - directamente desde el código.
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.
Notas y consejos
- •Verifica la conectividad del proxy: curl -x http://user:pass@proxy.sotaproxy.com:10000 https://httpbin.org/ip
- •Ante problemas de verificación SSL, establece verify=False en requests (no recomendado en producción) o añade el certificado CA del proxy.
- •La configuración de proxy en aiohttp usa connector=aiohttp.TCPConnector() y proxy=proxy_url en session.get().
FAQ
¿Cómo uso proxies rotativos con Python requests?
Establece el diccionario proxies con tu endpoint de SotaProxy una vez. La rotación ocurre del lado del servidor - no necesitas cambiar la URL del proxy entre solicitudes.
¿Funciona SotaProxy con Scrapy?
Sí. Establece DOWNLOADER_MIDDLEWARES y HTTP_PROXY en tu settings.py, o usa el paquete de middleware de proxy rotativo.
¿Cómo manejo los errores de autenticación del proxy?
Comprueba que el usuario y la contraseña de la URL del proxy estén codificados en URL si contienen caracteres especiales. Prueba primero con curl para aislar los problemas de autenticación de los del código.
Integraciones relacionadas
Obtén tus credenciales de proxy
Regístrate, recarga tu saldo y copia tu endpoint en Python. Tarda menos de 5 minutos.
Empezar