Selenium proxy setup in Python
Selenium passes the proxy address to Chrome as a launch flag, and that flag has no place for a username and password. The dependable way around it is a small forwarder on your own machine that adds the login for the browser. This guide builds one and shows how to use it.
Last updated:
Connection fields
Selenium can hand Chrome two of the four dashboard values directly. The other two go through a local forwarder.
A proxy line reads HOST:PORT:USERNAME:PASSWORD. In Selenium the host and port go into a Chrome argument, --proxy-server=http://HOST:PORT. Chrome ignores a username and password written into that argument, and Selenium has no proxy login setting of its own, so a browser started this way reaches the proxy without credentials and gets a 407.
A small program on 127.0.0.1 closes that gap. It accepts the browser's connection without a login and passes it to the proxy with your username and password added. It works the same way on every plan, because every plan accepts username:password:
- Browser to forwarder:
--proxy-server=http://127.0.0.1:8899, no credentials. - Forwarder to proxy:
HOST,PORT,USERNAMEandPASSWORDfrom your dashboard.
| Product | Host and port | Protocols | Authentication |
|---|---|---|---|
| Residential and Unlimited Residential | shown in your dashboard | HTTP, HTTPS and SOCKS5 on the same port | username:password |
| Rotating Mobile | shown in your dashboard | HTTP(S) and SOCKS5 on the same port | username:password |
| Mobile Proxy (Reset Link) | shown in your dashboard | HTTP(S) and SOCKS5 on the same port | username:password |
| Datacenter, ISP and IPv6 | shown with your order in the dashboard | HTTP(S) and SOCKS5 on separate ports | username:password |
HOST, PORT, USERNAME and PASSWORD in the examples are placeholders. Your dashboard shows the host, port, username and password for each plan: copy them from the Proxy generator.
HTTP(S) or SOCKS5
The forwarder speaks HTTP(S) to the proxy, so the protocol choice is made for you.
| Protocol | Residential and mobile plans | Datacenter, ISP and IPv6 | In Selenium with Chrome |
|---|---|---|---|
| HTTP(S) | host and port from your dashboard | HTTP(S) port shown with your order | Through the local forwarder, which adds the login. |
| SOCKS5 | same host and port | SOCKS5 port shown with your order | Not with a login: Chrome cannot authenticate to a SOCKS5 proxy. |
Chrome talks plain HTTP proxy protocol to the forwarder on 127.0.0.1, and the forwarder connects to the HTTP(S) port of your plan. HTTPS pages are tunnelled with CONNECT the whole way, so the TLS session stays between the browser and the site.
Authentication with a local forwarder
The forwarder uses only the Python standard library and runs next to your tests.
The script below listens on 127.0.0.1, adds a Proxy-Authorization header to the first request of every connection and relays the rest unchanged. Save it as forwarder.py, set UPSTREAM_HOST, UPSTREAM_PORT and PASSWORD to the values from your dashboard (Proxy generator), and leave it running in its own terminal.
"""Local forwarder for browsers that cannot send proxy credentials.
Listens on 127.0.0.1 without authentication and passes every connection to the
upstream proxy with a Proxy-Authorization header added to its first request.
That covers every HTTPS page, because the browser opens one CONNECT tunnel per
connection. Plain http:// pages that reuse a connection are not covered: only
the first request of a connection gets the header.
Usage: python forwarder.py [listen_port] [proxy_username]
"""
import asyncio
import base64
import sys
# Copy HOST, PORT, USERNAME and PASSWORD from your dashboard (Proxy generator).
UPSTREAM_HOST = "HOST"
UPSTREAM_PORT = "PORT"
PASSWORD = "PASSWORD"
LISTEN_PORT = int(sys.argv[1]) if len(sys.argv) > 1 else 8899
USERNAME = sys.argv[2] if len(sys.argv) > 2 else "USERNAME"
AUTH = base64.b64encode(f"{USERNAME}:{PASSWORD}".encode()).decode()
async def pipe(reader, writer):
try:
while data := await reader.read(65536):
writer.write(data)
await writer.drain()
except (ConnectionError, OSError):
pass
finally:
writer.close()
async def handle(client_reader, client_writer):
try:
head = await client_reader.readuntil(b"\r\n\r\n")
up_reader, up_writer = await asyncio.open_connection(UPSTREAM_HOST, int(UPSTREAM_PORT))
except (asyncio.IncompleteReadError, asyncio.LimitOverrunError, OSError, ValueError):
client_writer.close()
return
first_line, rest = head.split(b"\r\n", 1)
auth_line = b"Proxy-Authorization: Basic " + AUTH.encode() + b"\r\n"
up_writer.write(first_line + b"\r\n" + auth_line + rest)
await up_writer.drain()
await asyncio.gather(pipe(client_reader, up_writer), pipe(up_reader, client_writer))
async def main():
server = await asyncio.start_server(handle, "127.0.0.1", LISTEN_PORT)
print(f"forwarding 127.0.0.1:{LISTEN_PORT} -> {UPSTREAM_HOST}:{UPSTREAM_PORT} as {USERNAME}")
async with server:
await server.serve_forever()
if __name__ == "__main__":
asyncio.run(main())Then point Chrome at the local port:
# Start the forwarder first: python forwarder.py 8899 USERNAME
# (USERNAME, and HOST, PORT and PASSWORD inside forwarder.py, come from your dashboard: Proxy generator.)
from selenium import webdriver
opts = webdriver.ChromeOptions()
opts.add_argument("--proxy-server=http://127.0.0.1:8899")
driver = webdriver.Chrome(options=opts)
driver.get("https://api.ipify.org?format=json")
print(driver.find_element("tag name", "body").text)
driver.quit()The forwarder covers every HTTPS page, because the browser opens one CONNECT tunnel per connection. It is written for HTTPS targets: plain http:// pages that reuse a connection would need the header on every request, which this script does not add. It binds to the loopback address, so other machines cannot use it. Keep the password in that one file and out of your test code. Third-party packages that wrap the driver to add proxy logins exist as well; before you rely on one, check that it is still maintained and supports your Selenium version.
Rotation and sticky sessions
With the forwarder, rotation is set by the username you start it with.
The forwarder takes the listen port and the proxy username as arguments. Started with the plain USERNAME of a Residential plan, every new connection gets a new IP, so the parts of one page can leave from different addresses. Started with a session username, such as USERNAME-session-482913-ttl-600, every browser that uses that local port keeps the same IP for the ttl.
For several identities, run one forwarder per session on its own port and give each Chrome instance its own port and its own profile:
# Residential plan: USERNAME comes from your dashboard (Proxy generator).
# Terminal 1: one forwarder per identity, each with its own session number and local port
python forwarder.py 8899 USERNAME-session-482913-ttl-600
# Terminal 2
python forwarder.py 8900 USERNAME-session-615027-ttl-600
# Terminal 3: IPs from Germany, held for 600 seconds
python forwarder.py 8901 USERNAME-country-de-session-739104-ttl-600To change the IP of an identity, stop its forwarder and start it again with a new session number.
| Product | New IP | Same IP | Location |
|---|---|---|---|
| Residential and Unlimited Residential | USERNAME (every new connection) | USERNAME-session-482913-ttl-600 | USERNAME-country-de |
| Rotating Mobile | USERNAME (every new connection) | USERNAME-session-482913-ttl-600 | chosen in your dashboard |
| Mobile Proxy (Reset Link) | Change IP button or reset link | USERNAME keeps one IP for up to 24 hours | chosen in your dashboard |
| Datacenter, ISP and IPv6 | set in the Proxy generator | set in the Proxy generator | set in the Proxy generator |
On Residential and Unlimited Residential the username on its own rotates, so every new connection gets a new IP. For a sticky session add -session- with a number and -ttl- with the time in seconds. Sticky sessions last up to 24 hours; the dashboard offers 1 minute, 10 minutes, 30 minutes, 1 hour, 6 hours and 24 hours, or a custom time. Use a different session number for each account or task; a new number gives you a new IP. On Datacenter, ISP and IPv6, the Proxy generator of your order builds the username for you: copy the generated lines from there. Details are in the rotating proxies guide.
The third forwarder above asks for IPs from Germany. On Residential and Unlimited Residential, add -country- and a two-letter country code to the username, as in USERNAME-country-de, and combine it with a session when the identity should keep its IP. State and city are chosen in the Proxy generator, which adds them to the username for you. On mobile plans, set UPSTREAM_HOST and UPSTREAM_PORT to the host and port shown in your dashboard and pass USERNAME-session-482913-ttl-600 as the second argument for a sticky Rotating Mobile session.
On Rotating Mobile you choose All countries or a single country in your dashboard, and the carrier inside that country is picked automatically. The username carries only the session: without one, every new connection gets a new carrier IP.
On Rotating Mobile the session ID must be numbers only (digits 0–9); an ID with letters is ignored and the IP keeps rotating. The number is only an example: pick your own, such as a random 6-digit number, and use a different one for each account or task. The ttl value is how long you want to keep the IP, in seconds. Mobile networks can still change an IP on their own, so plan for an occasional change.
Mobile Proxy (Reset Link) keeps one carrier IP for up to 24 hours. Change it with the Change IP button or your reset link, once every 30 seconds; changing the location in your dashboard also gives you a new IP.
Test the connection
Verify the exit IP in the automated browser before running a test suite through it.
Load https://api.ipify.org?format=json and print the body, as the scripts above do. In a visible Chrome window you can also open the My IP tool; it should show the proxy's address, not the one of your machine.
This version runs headless, sets a page-load timeout and reports what went wrong:
# Start the forwarder first (HOST, PORT, USERNAME and PASSWORD from your dashboard: Proxy generator).
from selenium import webdriver
from selenium.common.exceptions import TimeoutException, WebDriverException
opts = webdriver.ChromeOptions()
opts.add_argument("--headless=new")
opts.add_argument("--proxy-server=http://127.0.0.1:8899")
driver = webdriver.Chrome(options=opts)
driver.set_page_load_timeout(30)
try:
driver.get("https://api.ipify.org?format=json")
print("exit IP:", driver.find_element("tag name", "body").text)
except TimeoutException:
print("timed out: check the proxy host, the port and your firewall")
except WebDriverException as error:
# Proxy problems surface here as net::ERR_... messages.
print("request failed:", error.msg)
finally:
driver.quit()Troubleshooting
Selenium surfaces Chrome's own error codes, so the message usually tells you which side failed.
407 Proxy Authentication Required
Chrome reached the proxy without valid credentials. Check the username and its suffix and the password in forwarder.py, that they belong to the plan whose host is in UPSTREAM_HOST, and that the forwarder's address is the one in --proxy-server. A login prompt in a visible browser window is the same condition: Chrome is talking to the proxy directly instead of through the forwarder, and Selenium cannot fill that prompt in.
Timeouts and net::ERR_ errors
net::ERR_PROXY_CONNECTION_FAILED means nothing is listening where Chrome was sent: the forwarder is not running or the local port differs. If the forwarder runs but cannot reach the proxy, it closes the connection and Chrome reports a tunnel or connection error; check the host, the port and any outbound firewall rule for the proxy port. net::ERR_TUNNEL_CONNECTION_FAILED means the proxy refused the tunnel. A TimeoutException on a page that loads slowly is governed by set_page_load_timeout(); raise it if the IP check itself is fast.
Target ports by plan
On Residential and Unlimited Residential plans, residential IPs connect to websites on ports 80 and 443 only: a URL that names another port, such as :8443, fails even when the proxy login is correct.
All target ports are open on Rotating Mobile and Mobile Proxy (Reset Link) plans.
Selenium proxy setup: frequently asked questions
Can I put the username and password in Chrome's --proxy-server flag?
No. Chrome ignores credentials in that flag. Run a local forwarder that adds the credentials for the browser, as shown on this page.
Which Core Proxies plans work with the forwarder?
All of them. The forwarder sends the username and password from your dashboard, so it works the same way on Residential, Rotating Mobile, Mobile Proxy (Reset Link), Datacenter, ISP and IPv6 plans.
Can I use sticky sessions with Selenium?
Yes. Start the forwarder with a sticky username, such as USERNAME-session-482913-ttl-600 on Residential, and every browser that uses that local port keeps one IP. Run one forwarder per session for several identities.
Does the forwarder work in headless mode and with Firefox?
Headless mode works the same way as headed mode. The forwarder is an ordinary local HTTP proxy, so a browser that accepts a proxy address can point at it; the scripts on this page were written for Chrome, and the forwarder is meant for HTTPS targets.
Is the local forwarder reachable from other machines?
No. It binds to 127.0.0.1, so only programs on the same machine can connect to it.
Run Selenium through Core Proxies
Create an account, choose your proxy type and plan, and copy the host, port, username and password from your dashboard. Activation is automatic after payment.
- Rotating and sticky sessions
- HTTP(S) and SOCKS5
- 24/7 support by email
Prices exclude VAT