Code and command line
Python Requests proxy setup
Requests is the library most Python scrapers start with, and it takes a proxy through one dictionary. The details that trip people up are elsewhere: the https key, encoding a password with symbols, SOCKS5 needing an extra package, and connection reuse inside a Session hiding your rotation.
The steps below build a small, reusable setup: a function that returns the right proxies dictionary for any country, city or session, a Session with sensible retries, and a check that prints the exit.
What do you need before adding a proxy in Python Requests?
Tick these off before the first step. Your login and password appear in your account once the first top-up of $40 or more has been credited.
| Requirement | Detail |
|---|---|
| Python 3.9 or newer | Any currently supported release. |
| requests | pip install requests. Add the socks extra only if you plan to use port 1080. |
| Login and password | Login looks like tp7k2m9_country-us. Keep the password in an environment variable. |
| A test URL | https://ipinfo.io/json returns the exit IP, city and country as JSON. |
Where do the proxy host, port and login go in Python Requests?
Work through the steps in order. Swap YOUR_PASSWORD for your proxy password and tp7k2m9 for your account name.
Install the packages
Plain Requests handles the HTTP port. The
socksextra pulls in PySocks, which Requests needs for anysocks5orsocks5hURL.pip install requestsFill the proxies dictionary
The dictionary maps the scheme of the target URL to a proxy. Both keys point to the same
http://gateway URL: thehttpskey does not mean the proxy itself speaks TLS, it means "use this proxy for https pages". Leaving it out is the most common reason a script quietly connects directly.import os import requests PASSWORD = os.environ.get("TOPPROXY_PASSWORD", "YOUR_PASSWORD") proxy = f"http://tp7k2m9_country-us:{PASSWORD}@proxy.topproxy.shop:8080" proxies = {"http": proxy, "https": proxy} r = requests.get("https://ipinfo.io/json", proxies=proxies, timeout=30) print(r.json())Tip.If your password contains @, : or /, wrap it with urllib.parse.quote(PASSWORD, safe="") before placing it in the URL.
Write a helper that builds the login
Location and session settings are joined to your account name with underscores. A small function keeps that format in one place, so the rest of the code only says which country, city or session it wants.
from urllib.parse import quote def topproxy(country="us", city=None, session=None, life=None, socks=False): login = f"tp7k2m9_country-{country}" if city: login += f"_city-{city}" if session: login += f"_session-{session}" if life: login += f"_life-{life}" pw = quote(PASSWORD, safe="") if socks: url = f"socks5h://{login}:{pw}@proxy.topproxy.shop:1080" else: url = f"http://{login}:{pw}@proxy.topproxy.shop:8080" return {"http": url, "https": url}Reuse a Session with retries
A
requests.Sessionkeeps connections open and lets you mount a retry policy once. Retries on 429 and 5xx answers smooth over a busy target. Set the proxies on the session so every call inherits them.from requests.adapters import HTTPAdapter from urllib3.util.retry import Retry s = requests.Session() s.proxies.update(topproxy("de")) retry = Retry(total=3, backoff_factor=1, status_forcelist=[429, 500, 502, 503, 504]) s.mount("https://", HTTPAdapter(max_retries=retry)) s.mount("http://", HTTPAdapter(max_retries=retry)) print(s.get("https://ipinfo.io/json", timeout=30).json()["country"])Tip.Environment variables such as HTTPS_PROXY override Session.proxies when trust_env is on. Set s.trust_env = False if a stray variable keeps sending traffic elsewhere.
Switch to SOCKS5 when a tool needs it
Pass
socks=Trueto the helper and the same code uses port 1080. Keep thesocks5hscheme so the exit resolves hostnames.r = requests.get("https://ipinfo.io/json", proxies=topproxy("ca", socks=True), timeout=30) print(r.json()["ip"])
How can you confirm the proxy is active in Python Requests?
Print the fields you care about. The country should match the code in your login, and the IP should not be the one your machine shows without a proxy.
info = requests.get("https://ipinfo.io/json", proxies=topproxy("us"), timeout=30).json()
print(info["ip"], info.get("city"), info["country"])The response shown here is shortened to the fields that matter. The region and time zone follow the exit, in this case Germany.
{
"ip": "198.51.100.47",
"city": "Frankfurt am Main",
"region": "Hesse",
"country": "DE",
"timezone": "Europe/Berlin"
}198.51.100.47 is an address reserved for documentation. A live check prints a real exit.
How do you switch between rotating and held IPs in Python Requests?
Fresh connections on a rotating login get fresh exits. A Session reuses its connection pool, so several calls on one Session can share an exit even without a session name. For a true new address per request, use plain requests.get or close the Session. For one stable address, add a session name and a life.
for _ in range(3):
print(requests.get("https://ipinfo.io/ip", proxies=topproxy("us"), timeout=30).text)How the login is put together
Every setting lives in the login, joined with underscores. Nothing else in Python Requests changes when you switch location or session.
| Part | Meaning | Rule |
|---|---|---|
| tp7k2m9 | Your account name | Always first. Yours is shown in your account and replaces tp7k2m9 in every example here. |
| _country-us | Exit country | Two-letter code in lowercase. 64 countries to choose from. |
| _city-new-york | Exit city, optional | Lowercase, spaces become hyphens. 172 cities in total. |
| _session-a1b2c3 | Session name, optional | Letters and digits you pick. Same name, same exit. New name, new exit. |
| _life-30 | Session life in minutes | Only with a session. Residential 1 to 120 minutes, mobile 1 to 60 minutes, long session ISP up to 12 hours (life 720). |
All parts togethertp7k2m9_country-us_city-new-york_session-a1b2c3_life-30
How do you choose an exit country or city in Python Requests?
Ask for a country with its two-letter code. Add a city in lowercase with hyphens. Cities have smaller pools than countries, so leave the city out unless the content really changes by city.
requests.get(url, proxies=topproxy("br"), timeout=30)Codes and city values for all 64 countries are listed on the proxy locations pages.
How do you fix a 407 or connection error in Python Requests?
Find the line that matches what you see. Most problems come down to the login, the port or the network you are on.
| Symptom | Likely cause | Fix |
|---|---|---|
ProxyError: Tunnel connection failed: 407 | The gateway refused the login or password. | Print the URL without the password part and compare the login with your account. Encode symbols in the password with quote(). |
InvalidSchema: Missing dependencies for SOCKS support | PySocks is not installed in this environment. | Run pip install "requests[socks]" in the same virtual environment. |
| The exit IP is your own address | Only the http key was set, so https pages went direct. | Set both http and https keys to the gateway URL. |
SSLError mentioning the proxy | The proxy URL starts with https://, which makes Requests try TLS to the gateway. | Start the proxy URL with http://. Your traffic to https sites is still encrypted inside the tunnel. |
| Same IP for every call in a loop | A Session kept one connection alive. | Call requests.get without a Session, or call s.close() between batches. |
Still stuck? Run the same login through the cURL check. If cURL connects, the issue is in the Python Requests settings. If it does not, write to support with the error text.
What kind of proxy pairs well with Python Requests?
All products sit behind the same gateway and share one prepaid balance, so moving from one to another means buying the other product and changing the login, nothing more.
- Rotating Residential ProxiesThe usual choice for Requests scrapers that need a new household address on most calls.$0.23 per GB
- Datacenter Proxy PoolCheapest per IP when the target is lightly protected and you rotate through a large list yourself.$0.58 per 100 IPs per month
- Unmetered Residential ProxiesPriced by the day, so a script that runs around the clock does not need a GB counter.$11.90 per day
Calling pages from code at scale? The TopProxy API docs cover the Scraping API, which renders pages and retries on its own.
What else do Python Requests users ask about proxies?
Why does the https key also start with http://?
The key names the scheme of the page you request, and the value is how to reach the proxy. TopProxy accepts plain HTTP on port 8080 and opens a CONNECT tunnel for https pages, so the page stays encrypted while the connection to the gateway itself is plain HTTP.
Can I use aiohttp or httpx with the same login?
Yes. httpx takes proxy="http://login:password@proxy.topproxy.shop:8080" on the client, and aiohttp takes proxy= on each request. The login format and ports do not change between libraries.
How many threads can share one login?
Rotating logins have no per-login thread limit on our side. The practical limit is how hard you want to hit the target site. Start with a few workers and raise the number while watching for 429 answers.
Where should the password live?
In an environment variable or a secrets manager, never in the repository. The helper on this page reads TOPPROXY_PASSWORD and falls back to a stand-in value so the code runs while you test.
Does Requests verify certificates through the proxy?
Yes. With an http:// proxy URL, Requests tunnels to the target and checks the target certificate as usual. Keep verify at its default of True.
Related setup guides
- Scrapyrequest.meta proxy per request, a small middleware for rotation and sticky crawls, and throttling that fits a gateway.
- cURLOne terminal command to prove your login works, then SOCKS5 with remote DNS and a reusable config file.
- PlaywrightProxy server, username and password at launch or per context, in Node.js and Python, with one location per context.
- SeleniumChrome cannot take a proxy password from a flag. Two working routes: a small auth extension, or Selenium Wire.
Ready to connect Python Requests?
Open an account, add $40 or more in crypto, and your login and password are waiting in the account area.