Реферальна програма
Розробка

Налаштування проксі у Scrapy

Додайте ротаційні проксі у вашого Scrapy-павука двома рядками конфіга.

Scrapy - найпопулярніший Python-фреймворк для скрапінгу. SotaProxy інтегрується як стандартний HTTP-проксі через вбудований проксі-middleware Scrapy. Задайте його в settings.py - і кожен запит вашого павука автоматично йтиме через проксі.

Посібник із налаштування

1

Увімкніть проксі-middleware в settings.py

python
# settings.py
DOWNLOADER_MIDDLEWARES = {
    'scrapy.downloadermiddlewares.httpproxy.HttpProxyMiddleware': 110,
}

HTTP_PROXY = "http://YOUR_USERNAME:YOUR_PASSWORD@proxy.sotaproxy.com:10000"

Додайте ці два налаштування в settings.py вашого Scrapy-проекту. Усі запити павука автоматично йтимуть через SotaProxy.

2

Проксі на запит (опційно)

python
# In your spider
def start_requests(self):
    for url in self.start_urls:
        yield scrapy.Request(
            url,
            meta={'proxy': 'http://YOUR_USERNAME:YOUR_PASSWORD@proxy.sotaproxy.com:10000'},
        )

Задайте проксі на запит у словнику meta, якщо для різних URL потрібні різні конфігурації проксі.

3

Гео-таргетинг у Scrapy

python
# Target US IPs for all requests
HTTP_PROXY = "http://YOUR_USERNAME_c_US:YOUR_PASSWORD@proxy.sotaproxy.com:10000"

# Or per-request targeting
meta={'proxy': 'http://YOUR_USERNAME_c_DE:YOUR_PASSWORD@proxy.sotaproxy.com:10000'}

Додайте _c_XX до імені користувача. Використовуйте таргетинг на запит, коли різним URL потрібні різні гео.

Автоматизуй через SotaProxy API

Усе описане вище працює без відкриття дашборда. З API-ключем Scrapy може отримувати свіжі дані проксі, купувати нові та продовжувати ті, що спливають, - прямо з коду.

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},
)
Документація API

Proxy credentials in a Scrapy project

Scrapy ships the middleware you need. Point request.meta at our endpoint and let HttpProxyMiddleware handle the rest:

Rotating residential
login:password@proxy.sotaproxy.com:10000
Pinned to a country
login_c_US:password@proxy.sotaproxy.com:10000
Sticky for 15 minutes
login_c_US_s_42_ttl_15m:password@proxy.sotaproxy.com:10000
Static address (ISP, datacenter)
login:password@your-ip:50100, SOCKS5 on 50101

Put the login and password in the proxy URL itself. Scrapy reads credentials from the URL and turns them into the Proxy-Authorization header for you.

One address per request, or one per spider

Set the proxy in meta and you control rotation per request without any third-party middleware:

Python: rotate inside start_requests

import itertools, scrapy

BASE = "proxy.sotaproxy.com:10000"

class ShopSpider(scrapy.Spider):
    name = "shop"
    custom_settings = {
        "CONCURRENT_REQUESTS": 32,
        "CONCURRENT_REQUESTS_PER_DOMAIN": 8,
        "DOWNLOAD_TIMEOUT": 30,
        "RETRY_TIMES": 2,
    }

    def start_requests(self):
        sessions = itertools.cycle(range(1, 11))
        for url in self.urls:
            login = f"login_c_US_s_{next(sessions)}_ttl_15m"
            yield scrapy.Request(
                url,
                meta={"proxy": f"http://{login}:password@{BASE}"},
                headers={"Accept-Encoding": "gzip"},
            )
  • Ten session ids give you ten stable addresses that survive redirects. Drop the _s_ part entirely and every request lands on a new one.
  • Raise CONCURRENT_REQUESTS rather than hammering one address. We do not cap concurrent connections, target sites do.
  • DOWNLOAD_TIMEOUT defaults to 180 seconds. On a residential route 30 is a better tradeoff between patience and throughput.
  • AutoThrottle plays well with proxies. Leave it on for unfamiliar targets and it will find a rate that does not trip rate limits.

Scrapy details that cost you data

Retry middleware reuses the same proxy

A retried request carries the original meta, including the address that just failed. Set a fresh proxy in the retry or write a tiny middleware that does.

Cookies crossing sessions

Scrapy keeps one cookiejar by default. When addresses rotate under it, the site sees one session hopping between countries. Use cookiejar per session id.

robots.txt fetched without the proxy

ROBOTSTXT_OBEY sends its own request. It goes through the same middleware, but the response is cached per domain, so a blocked fetch silently stops the crawl.

Assuming meta persists across redirects

It does, which is the point, but it means a redirect chain stays on one address. That is what you want for logins and not what you want for wide crawls.

Нотатки та поради

  • Задайте CONCURRENT_REQUESTS для керування паралельністю. Висока паралельність з одного ендпоінту проксі - це нормально, ротація на боці сервера.
  • Увімкніть RETRY_ENABLED = True і RETRY_HTTP_CODES = [403, 429, 503] для автоматичних ретраїв на блокуваннях.
  • Для випадкових сесій на запит генеруйте унікальний ID сесії на кожен запит і додавайте його до імені користувача.

FAQ

Чи ротує Scrapy IP автоматично з SotaProxy?

Так. З ротаційними резидентними проксі кожен запит через один ендпоінт отримує інший IP. Middleware для ротації проксі не потрібен - ротація на боці сервера.

Як обробляти блокування 403 у Scrapy?

Додайте 403 до RETRY_HTTP_CODES. Для сайтів, що блокують за user-agent, ротуйте user-agent через middleware scrapy-fake-useragent.

Отримай облікові дані проксі

Зареєструйся, поповни баланс і скопіюй ендпоінт у Scrapy. Займе менше 5 хвилин.

Почати