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

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

Налаштуйте ротаційні проксі у Selenium WebDriver для Chrome і Firefox.

Selenium WebDriver автоматизує браузери для тестування та скрапінгу. Налаштуйте SotaProxy у ChromeOptions або FirefoxProfile браузера перед запуском.

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

1

Chrome з Python

python
from selenium import webdriver
from selenium.webdriver.chrome.options import Options

options = Options()
options.add_argument('--proxy-server=http://proxy.sotaproxy.com:10000')

driver = webdriver.Chrome(options=options)

# Handle authentication via extension or CDP
driver.get("https://httpbin.org/ip")
print(driver.page_source)
driver.quit()

Chrome не підтримує автентифікацію проксі через аргументи командного рядка. Для проксі з автентифікацією використовуйте розширення Chrome або підхід через Chrome DevTools Protocol (CDP) нижче.

2

Chrome з автентифікацією через CDP (Python)

python
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import json, base64

PROXY_HOST = "proxy.sotaproxy.com"
PROXY_PORT = 10000
PROXY_USER = "YOUR_USERNAME"
PROXY_PASS = "YOUR_PASSWORD"

# Create auth extension
manifest = {
    "version": "1.0.0",
    "manifest_version": 2,
    "name": "Proxy Auth",
    "permissions": ["proxy", "webRequest", "webRequestBlocking", "<all_urls>"],
    "background": {"scripts": ["background.js"]},
}
background_js = f"""
var config = {{
    mode: "fixed_servers",
    rules: {{
        singleProxy: {{
            scheme: "http",
            host: "{PROXY_HOST}",
            port: {PROXY_PORT},
        }},
    }}
}};
chrome.proxy.settings.set({{value: config, scope: "regular"}}, function(){{}});

chrome.webRequest.onAuthRequired.addListener(
    function(details) {{
        return {{authCredentials: {{username: "{PROXY_USER}", password: "{PROXY_PASS}"}}}};
    }},
    {{urls: ["<all_urls>"]}},
    ["blocking"]
);
"""

import zipfile, os
ext_path = "/tmp/proxy_auth.zip"
with zipfile.ZipFile(ext_path, 'w') as zp:
    zp.writestr("manifest.json", json.dumps(manifest))
    zp.writestr("background.js", background_js)

options = Options()
options.add_extension(ext_path)
driver = webdriver.Chrome(options=options)
driver.get("https://httpbin.org/ip")
print(driver.page_source)

Chrome вимагає розширення для обробки автентифікації проксі. Тут створюється мінімальне розширення в пам’яті.

3

Firefox з Python

python
from selenium import webdriver
from selenium.webdriver.firefox.options import Options

options = Options()
options.set_preference("network.proxy.type", 1)
options.set_preference("network.proxy.http", "proxy.sotaproxy.com")
options.set_preference("network.proxy.http_port", 10000)
options.set_preference("network.proxy.ssl", "proxy.sotaproxy.com")
options.set_preference("network.proxy.ssl_port", 10000)

driver = webdriver.Firefox(options=options)

# Firefox prompts for credentials - handle via alert
driver.get("https://httpbin.org/ip")

Firefox підтримує налаштування проксі нативно через параметри профілю. Обробіть спливне вікно автентифікації через driver.switch_to.alert.

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

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

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

The authentication gap in Selenium

Chrome and Firefox drivers accept a proxy address, but neither accepts a username and password through the standard capability. This is the single biggest source of confusion on this page:

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

Two ways out: run selenium-wire, which handles authenticated proxies natively, or generate a small Chrome extension that supplies the credentials. Both are shown below.

selenium-wire, or an extension you generate

selenium-wire is the shorter road and takes the login with suffixes exactly as we hand it out:

Python: selenium-wire with an authenticated proxy

from seleniumwire import webdriver

login = "login_c_US_s_3_ttl_1h"
opts = {
    "proxy": {
        "http": f"http://{login}:password@proxy.sotaproxy.com:10000",
        "https": f"http://{login}:password@proxy.sotaproxy.com:10000",
        "no_proxy": "localhost,127.0.0.1",
    }
}
driver = webdriver.Chrome(seleniumwire_options=opts)
driver.get("https://api.ipify.org")
  • Change the session id and restart the driver to change address. There is no way to swap the proxy under a running Chrome session.
  • Keep no_proxy for localhost, otherwise the driver tries to reach chromedriver through the proxy and the session never starts.
  • selenium-wire intercepts traffic in Python, which costs throughput. For pure scraping, requests or Playwright will be several times faster.
  • If you cannot add the dependency, build a two-file extension with a background script that answers the auth challenge and load it with add_extension.

Selenium specifics

Credentials in the --proxy-server flag are ignored

Exactly as in Puppeteer. Chrome takes host and port and nothing else, then challenges every request with 407.

A popup asks for the password

When Chrome cannot answer the proxy challenge it shows a native dialog that Selenium cannot click. That dialog is the symptom, not the cause.

The proxy applies to the whole browser

Per-tab addresses do not exist. One driver equals one address, so parallel identities mean parallel drivers.

Stale drivers hold sessions open

Always quit the driver. Abandoned Chrome processes keep their connection to the endpoint and quietly eat your concurrency.

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

  • Для конвеєрів автотестування Playwright простіше налаштувати з проксі з автентифікацією, ніж Selenium Chrome.
  • Сетапи Selenium Grid можуть налаштовувати проксі на рівні ноди - дивіться документацію з конфігурації вашого Grid.

FAQ

Чому Chrome не підтримує автентифікацію проксі у Selenium?

Chrome прибрав підтримку автентифікації проксі через командний рядок із міркувань безпеки. Використовуйте метод із розширенням вище або перемкніться на Firefox/Playwright для простішого налаштування проксі з автентифікацією.

Чи можна використовувати SotaProxy із Selenium Grid?

Так. Налаштуйте проксі в capabilities браузера під час реєстрації нод або передавайте налаштування проксі на тест у desired capabilities.

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

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

Почати