ProxyProviders Quick Start Documentationο
ProxyProvidersο
One interface for proxy vendors, many Python clients.
Get proxies from Webshare, Bright Data or your own list, and use them with requests, httpx, aiohttp, Playwright, Scrapy, Crawlee or curl without writing vendor-specific code. Swap providers by changing one line.
import requests
from proxyproviders import Webshare, ProxyFormat
provider = Webshare(api_key="your-api-key") # or BrightData(...), or ProxyList([...])
proxy = provider.get_proxy()
response = requests.get(
"https://httpbin.org/ip", proxies=proxy.format(ProxyFormat.REQUESTS)
)
Table of Contentsο
Installationο
python -m pip install proxyproviders
Python 3.10 or newer. The full documentation is here, and there are runnable examples in the repository.
Using an AI coding assistant? Point it at llms.txt, a short summary of the API written for assistants.
πΊ Video Tutorial: Watch the quick start guide on YouTube for a walkthrough of getting started with ProxyProviders.
What It Doesο
Every proxy vendor has its own API, and every HTTP client wants its proxy in a different shape. ProxyProviders sits between the two:
Webshare | Bright Data | your own list
β
ProxyProvider β Proxy
β
requests | httpx | aiohttp | Playwright | Scrapy | Crawlee | curl
Provider API handled for you. Proxies are fetched from the vendor, cached, and refreshed on an interval.
One
Proxymodel. Host, port, credentials, country and protocols look the same whichever vendor they came from.One line to hand it to your client.
proxy.format(...)produces what each client expects, with credentials percent-encoded correctly.Vendor-neutral code. Anything written against
ProxyProviderworks with every provider, so switching vendor does not touch the rest of your application.
Rotation and retries are available if you want them (RotatingSession), and stay out of the way if your framework already does that.
Works Withο
Client |
How to pass the proxy |
Format |
|---|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
urllib |
|
|
|
|
|
|
|
|
Other tools |
|
|
Anything else |
|
|
requests, httpx, aiohttp, urllib and curl are tested in CI by sending a real request through a local proxy with each clientβs current release.
Supported Proxy Providersο
Provider |
Class |
Notes |
|---|---|---|
Webshare |
|
10 free datacenter proxies to try it out |
Bright Data |
|
Super proxy or one proxy per IP in the zone |
Any other vendor |
|
Your own list of proxy URLs or |
Getting credentials:
Webshare: create an account here (affiliate link), then generate a token in the API tab.
Bright Data: create an account here (affiliate link), then create an API token in the account settings.
Keep API tokens out of your code and repository; the examples below read them from environment variables. Each providerβs options are in the provider documentation. Donβt see your vendor? Add a provider or open an issue.
Quick Start Guideο
List the proxies from a provider:
import os
from proxyproviders import Webshare
provider = Webshare(api_key=os.environ["WEBSHARE_API_KEY"])
proxies = provider.list_proxies()
print(proxies) # passwords are left out of the printed output
Or take one at a time. get_proxy() cycles through the list in order by default:
proxy = provider.get_proxy()
print(proxy.proxy_address, proxy.port, proxy.country_code)
Providers take their own options. Webshare passes search_params to the Webshare API, so this returns only proxies based in the US:
provider = Webshare(
api_key=os.environ["WEBSHARE_API_KEY"], search_params={"country_code_in": "US"}
)
Because every provider has the same interface, code written against ProxyProvider does not care which vendor is behind it:
import os
import requests
from proxyproviders import BrightData, ProxyFormat, ProxyProvider, Webshare
def fetch_ip(provider: ProxyProvider) -> str:
proxy = provider.get_proxy()
response = requests.get(
"https://httpbin.org/ip", proxies=proxy.format(ProxyFormat.REQUESTS)
)
return response.json()["origin"]
fetch_ip(Webshare(api_key=os.environ["WEBSHARE_API_KEY"]))
fetch_ip(BrightData(api_key=os.environ["BRIGHTDATA_API_KEY"], zone="my_zone"))
That is how other libraries, such as my TikTokAPI package, accept any proxy vendor without knowing about it.
Using Proxies With Your HTTP Clientο
Every example below starts with a provider, which can be any provider from the table above.
Python requests With Rotating Proxiesο
import requests
from proxyproviders import ProxyFormat
proxy = provider.get_proxy()
response = requests.get(
"https://httpbin.org/ip", proxies=proxy.format(ProxyFormat.REQUESTS)
)
Each get_proxy() call returns the next proxy, so calling it per request rotates through your proxies. To have rotation and retries done for you, use RotatingSession.
httpx Proxyο
httpx (0.26 or newer) takes one proxy URL in its proxy= argument, for both the sync and async clients:
import httpx
from proxyproviders import ProxyFormat
with httpx.Client(proxy=provider.get_proxy().format(ProxyFormat.HTTPX)) as client:
response = client.get("https://httpbin.org/ip")
async with httpx.AsyncClient(
proxy=provider.get_proxy().format(ProxyFormat.HTTPX)
) as client:
response = await client.get("https://httpbin.org/ip")
aiohttp Proxyο
import aiohttp
from proxyproviders import ProxyFormat
async with aiohttp.ClientSession() as session:
async with session.get(
"https://httpbin.org/ip", proxy=provider.get_proxy().format(ProxyFormat.AIOHTTP)
) as response:
print(await response.json())
Playwright Proxy in Pythonο
from playwright.sync_api import sync_playwright
from proxyproviders import ProxyFormat
with sync_playwright() as p:
browser = p.chromium.launch()
context = browser.new_context(
proxy=provider.get_proxy().format(ProxyFormat.PLAYWRIGHT)
)
page = context.new_page()
page.goto("https://httpbin.org/ip")
Give each browser context its own get_proxy() call to spread contexts across proxies. The same dictionary works for p.chromium.launch(proxy=...).
Scrapy Proxyο
Scrapyβs built-in HttpProxyMiddleware reads the proxy from request.meta and takes the credentials out of the URL:
import scrapy
from proxyproviders import ProxyFormat
class IpSpider(scrapy.Spider):
name = "ip"
def start_requests(self):
yield scrapy.Request(
"https://httpbin.org/ip",
meta={"proxy": provider.get_proxy().format(ProxyFormat.SCRAPY)},
)
Crawlee for Python Proxyο
Crawlee rotates proxies and manages sessions itself, so hand it the whole list:
from crawlee.proxy_configuration import ProxyConfiguration
proxy_configuration = ProxyConfiguration(
proxy_urls=[proxy.to_url() for proxy in provider.list_proxies()]
)
curl and Subprocessesο
import os
import subprocess
from proxyproviders import ProxyFormat
proxy = provider.get_proxy()
# As curl arguments: ["-x", "http://user:pass@host:port"]
subprocess.run(["curl", *proxy.format(ProxyFormat.CURL), "https://httpbin.org/ip"])
# Or as HTTP_PROXY / HTTPS_PROXY for any program that reads them
subprocess.run(
["curl", "https://httpbin.org/ip"],
env={**os.environ, **proxy.format(ProxyFormat.ENV)},
)
Use Your Own Proxy Listο
If your vendor has no provider here, or you simply have a list of proxies, ProxyList gives them the same interface as everything else:
from proxyproviders import ProxyList
provider = ProxyList(
[
"http://user:pass@203.0.113.7:8080",
"203.0.113.8:8080:user:pass",
"socks5://user:pass@203.0.113.9:1080",
]
)
# Or one proxy per line from a file (blank lines and # comments are skipped)
provider = ProxyList.from_file("proxies.txt")
A single proxy can be parsed with Proxy.from_string(...), which accepts a URL, user:pass@host:port, host:port or host:port:user:pass.
Automatic Rotation and Retriesο
RotatingSession is a requests.Session that picks a proxy for every request. If a request cannot get through its proxy, that proxy is set aside for a while and the request is sent again through the next one:
from proxyproviders import RotatingSession
session = RotatingSession(provider, max_retries=3)
response = session.get("https://httpbin.org/ip", timeout=10)
print(response.json(), session.last_proxy)
It is opt-in: nothing changes for code that calls get_proxy() itself. What it treats as a failed proxy, and when it sends the request again:
Could not connect to the proxy, or open a tunnel through it: retried for any HTTP method, because the request never reached the target.
Any other connection error or timeout, such as a proxy that drops the connection or stops responding: retried for
GET,HEADandOPTIONSonly. APOSTmay already have been acted on, so the error is raised instead of sending it twice.A
407 Proxy Authentication Requiredresponse, or any status you list inretry_statuses: retried for any method.
Ordinary error statuses such as 404 or 500 are returned as usual. File uploads and streamed bodies are sent once and never retried. Deciding that a response means your proxy is blocked is up to you, for example:
session = RotatingSession(provider, max_retries=3, retry_statuses={403, 429})
For httpx 0.26 or newer, sync or async, the same behaviour comes as a transport. Install it with pip install "proxyproviders[httpx]":
import httpx
from proxyproviders.httpx_transport import AsyncRotatingTransport, RotatingTransport
with httpx.Client(transport=RotatingTransport(provider, max_retries=3)) as client:
response = client.get("https://httpbin.org/ip")
async with httpx.AsyncClient(transport=AsyncRotatingTransport(provider)) as client:
response = await client.get("https://httpbin.org/ip")
Reporting Failed Proxiesο
When you make requests yourself, tell the provider about a proxy that failed and get_proxy() will avoid it for failure_cooldown seconds (60 by default):
import requests
from proxyproviders import ProxyFormat
proxy = provider.get_proxy()
try:
response = requests.get(url, proxies=proxy.format(ProxyFormat.REQUESTS), timeout=10)
except requests.exceptions.ProxyError:
provider.report_failure(proxy)
provider.report_success(proxy) puts it back early, and provider.available_proxies() lists the ones not currently set aside. If every proxy has failed, get_proxy() still returns one instead of raising. This works the same with every HTTP client, sync or async.
Choosing Which Proxy You Getο
get_proxy() takes a selection algorithm. The default is round robin.
from proxyproviders.algorithms import First, Random, RoundRobin
proxy = provider.get_proxy() # RoundRobin: next proxy in order
proxy = provider.get_proxy(Random()) # a random proxy
proxy = provider.get_proxy(First()) # always the first proxy
# A RoundRobin you create keeps its own position, separate from the provider's default
round_robin = RoundRobin()
proxy1 = provider.get_proxy(round_robin)
proxy2 = provider.get_proxy(round_robin) # next in sequence
Write your own by subclassing Algorithm:
from typing import List
from proxyproviders import Proxy
from proxyproviders.algorithms import Algorithm
class USProxyAlgorithm(Algorithm):
"""Prefers US proxies, falls back to the first available."""
def select(self, proxies: List[Proxy]) -> Proxy:
for proxy in proxies:
if proxy.country_code == "US":
return proxy
return proxies[0]
proxy = provider.get_proxy(USProxyAlgorithm())
Configurationο
Options shared by every provider live in ProxyConfig (full reference):
Option |
Default |
Meaning |
|---|---|---|
|
600 |
Seconds before the proxy list is fetched again. 0 fetches once and never refreshes. |
|
30 |
Seconds to wait on each call to the providerβs API |
|
30 |
If a refresh fails, the previous list keeps being served and the API is tried again after this many seconds |
|
60 |
Seconds |
import os
import time
from proxyproviders import ProxyConfig, Webshare
config = ProxyConfig(refresh_interval=3)
ws = Webshare(api_key=os.environ["WEBSHARE_API_KEY"], config=config)
ws.list_proxies() # calls the API
ws.list_proxies() # cached
time.sleep(5)
ws.list_proxies() # calls the API again, since more than 3s have passed
list_proxies() and get_proxy() are safe to call from several threads.
SOCKS Proxiesο
A proxy whose protocols only lists a SOCKS scheme, e.g. ["socks5"], is formatted with that scheme for every client:
proxy.format(ProxyFormat.REQUESTS)
# {'http': 'socks5://user:pass@host:1080', 'https': 'socks5://user:pass@host:1080'}
Your HTTP client needs SOCKS support for this to work. For requests, install it with:
python -m pip install "proxyproviders[socks]"
httpx needs httpx[socks]. aiohttp and Scrapy have no built-in SOCKS support.
Making Your Own Proxy Providerο
Subclass ProxyProvider and return a list of Proxy objects from _fetch_proxies. Caching, refreshing, selection, formatting and failure reporting then work without any more code:
from typing import List, Optional
from proxyproviders import Proxy, ProxyConfig, ProxyProvider
class MyProxyProvider(ProxyProvider):
def __init__(self, config: Optional[ProxyConfig] = None):
super().__init__(config=config)
def _fetch_proxies(self) -> List[Proxy]:
# Call your vendor's API here and convert each entry
return [
Proxy(
id="1",
username="username",
password="password",
proxy_address="192.168.1.1",
port=80,
)
]
provider = MyProxyProvider()
proxy = provider.get_proxy()
If you write one for a vendor other people use, please contribute it back. CONTRIBUTING.md has the steps, and the repository includes an add-provider skill that walks a coding agent such as Claude Code through the whole process.
How to Support The Projectο
Star the repo π
Consider sponsoring me on GitHub
Send me an email or a LinkedIn message about what youβre doing with it :D
Submit PRs for issues or any new providers/features :)
Note: If you want to learn how to web scrape websites check my free and open-source course for learning everything web scraping
ProxyProvider Shared Interfaceο
- class proxyproviders.proxy_provider.ProxyConfig(refresh_interval: float = 600, timeout: float = 30, refresh_retry_delay: float = 30, failure_cooldown: float = 60)[source]ο
Bases:
objectProvides standard shared configuration options for all proxy providers.
Example:
from proxyproviders import Webshare, ProxyConfig config = ProxyConfig(refresh_interval=5) proxy_provider = Webshare(api_key="your-api-key", config=config)
- refresh_interval: float = 600ο
Duration in seconds after which the proxy list is refreshed to fetch new proxies. Set to 0 to disable automatic refreshing after the initial fetch.
- timeout: float = 30ο
Timeout in seconds for each request to the providerβs API, so a stalled connection raises instead of hanging forever.
- refresh_retry_delay: float = 30ο
After an automatic refresh fails and the previous proxy list is served instead, wait this many seconds before trying the providerβs API again.
- failure_cooldown: float = 60ο
How long, in seconds,
ProxyProvider.get_proxy()avoids a proxy after it was passed toProxyProvider.report_failure().
- class proxyproviders.proxy_provider.ProxyProvider(config: ProxyConfig | None = None)[source]ο
Bases:
ABCBase class for all proxy providers that provides shared functionality across all providers.
Youβll need to use a specific provider to fetch proxies and this shouldnβt directly be initialized. However, this class is useful for type hinting and for creating custom providers that are not included in the library, although consider contributing them to the library if you are making them.
- Parameters:
config β Configuration for the proxy provider. View the ProxyConfig class docs for more information.
- config: ProxyConfigο
- list_proxies(force_refresh: bool = False) List[Proxy][source]ο
Returns the stored proxies, fetching them from the provider first when they are missing or older than
refresh_interval.Safe to call from several threads: when the list is stale only one thread fetches and the others wait for its result.
If an automatic refresh fails and an earlier list is available, that list is returned and a warning is logged, so one failed call to the providerβs API does not take your proxies away. The error is raised when there is nothing to fall back on, or when
force_refreshis True.- Parameters:
force_refresh β If True, fetches new proxies even if the list is not considered stale.
- get_proxy(algorithm: Algorithm | None = None) Proxy[source]ο
Get a single proxy using the specified selection algorithm.
- Parameters:
algorithm β Selection algorithm to use. If None, uses the providerβs default RoundRobin algorithm.
- Returns:
Selected proxy
- Raises:
ValueError β If no proxies are available
Example
>>> from proxyproviders import Webshare >>> from proxyproviders.algorithms import Random, RoundRobin >>> >>> provider = Webshare(api_key="your-key") >>> >>> # Uses default RoundRobin (cycles through proxies) >>> proxy = provider.get_proxy() >>> >>> # Uses Random selection >>> proxy = provider.get_proxy(Random()) >>> >>> # One-liner with requests >>> import requests >>> from proxyproviders.models.proxy import ProxyFormat >>> requests.get("https://httpbin.org/ip", proxies=provider.get_proxy().format(ProxyFormat.REQUESTS))
- report_failure(proxy: Proxy, cooldown: float | None = None) None[source]ο
Tell the provider a proxy just failed, so
get_proxy()avoids it for a while.Nothing calls this for you unless you use
RotatingSession; it is how your own code feeds back a connection error, a ban or a bad response. The proxy stays inlist_proxies()and comes back into rotation once the cooldown has passed. If every proxy is cooling down,get_proxy()still returns one.- Parameters:
proxy β The proxy that failed
cooldown β Seconds to avoid it for. Defaults to
ProxyConfig.failure_cooldown.
Example
>>> proxy = provider.get_proxy() >>> try: ... requests.get(url, proxies=proxy.format(ProxyFormat.REQUESTS), timeout=10) ... except requests.exceptions.ProxyError: ... provider.report_failure(proxy)
- report_success(proxy: Proxy) None[source]ο
Clear a failure reported for a proxy, putting it back into rotation right away.
- available_proxies() List[Proxy][source]ο
Like
list_proxies(), without the proxies currently cooling down afterreport_failure().
ProxyProviders Supported Providersο
Current Providers Supported:
Webshare.io (referral link) - try out 10 free datacenter proxies
BrightData (affiliate link)
ProxyList- your own list of proxies from any other vendor
Donβt see a provider you need? Open an issue or submit a PR!
- class proxyproviders.providers.brightdata.BrightData(api_key: str, zone: str, username_suffix: str | None = None, use_super_proxy: bool | None = True, config: ProxyConfig | None = None)[source]ο
Bases:
ProxyProviderBrightData (formerly luminati) is a proxy provider that offers residential and datacenter proxies.
Create an account here (affiliate link).
You can find your API key in the account settings here then create βadd tokenβ with scope βlimitβ (BrightData article for more info)
The BrightData API documentation is here
- Parameters:
api_key β Your BrightData API key
zone β The zone ID/name to fetch proxies for (you can get this from the BrightData dashboard)
username_suffix β Optional suffix to append to the username more info allows you to target region, city, etc. (requires use_super_proxy=True)
use_super_proxy β Optional flag to use super proxy instead of targeting specific IPs, this is enabled by default. If you want to target specific IPs or have consistent IPs for a session, set this to False.
config β Configuration for the proxy provider. View the ProxyConfig class docs for more information.
Example:
from proxyproviders import BrightData # Initialize the BrightData API client with an API key and a zone proxy_provider = BrightData(api_key="your-api-key", zone="my_zone") # Fetch proxies proxies = proxy_provider.list_proxies() # returns one proxy for super proxy by default # If you want to manage specific IPs proxy_provider = BrightData(api_key="your-api-key", zone="my_zone", use_super_proxy=False) proxies = proxy_provider.list_proxies() # returns multiple proxies for each IP in the zone (potentially thousands)
- get_active_zones() Any[source]ο
Fetches active zones from BrightData API.
Response:
[ { "name": "zone1", "type": "dc", } ]
- get_zone_username(zone: str) str[source]ο
Fetches zone username for the given zone ID from BrightData API.
Note: this isnβt directly an API endpoint, Iβm sort of reconstructing some things here and it seems to behave a little weird.
- Parameters:
zone β The zone ID to fetch username for
- class proxyproviders.providers.proxy_list.ProxyList(proxies: Iterable[str | Proxy], config: ProxyConfig | None = None)[source]ο
Bases:
ProxyProviderA provider for proxies you already have, from any vendor.
Use it when your vendor has no provider here yet, or when you manage the list yourself. You get the same interface as every other provider: selection algorithms, output formats, failure reporting and
RotatingSession.- Parameters:
proxies β The proxies, each either a
Proxyor text in any formProxy.from_string()accepts: a URL such ashttp://user:pass@host:portorsocks5://host:port, orhost:port:user:passconfig β Configuration for the proxy provider. View the ProxyConfig class docs for more information.
- Raises:
ValueError β If an entry cannot be parsed, or the list is empty
Example:
from proxyproviders import ProxyList provider = ProxyList( [ "http://user:pass@203.0.113.7:8080", "203.0.113.8:8080:user:pass", "socks5://user:pass@203.0.113.9:1080", ] ) proxy = provider.get_proxy() # Or one proxy per line from a file, ignoring blank lines and # comments provider = ProxyList.from_file("proxies.txt")
- classmethod from_file(path: str | Path, config: ProxyConfig | None = None) ProxyList[source]ο
Load proxies from a text file with one proxy per line.
Blank lines and lines starting with
#are skipped.- Parameters:
path β Path to the file
config β Configuration for the proxy provider
Rotating Sessionο
An opt-in requests.Session that picks a proxy for every request.
Nothing else in the package uses this module. Import it when you want rotation and
retries handled for you instead of calling provider.get_proxy() yourself.
- class proxyproviders.session.RotatingSession(provider: ProxyProvider, algorithm: Algorithm | None = None, max_retries: int = 2, retry_statuses: Collection[int] = ())[source]ο
Bases:
SessionA
requests.Sessionthat routes each request through a proxy from a provider.Every request asks the provider for a proxy. If the request fails to get through the proxy, the proxy is reported with
report_failure()and the request is tried again on the next one, up tomax_retriesmore times. It works with any provider, includingProxyList.What counts as a failed proxy, and when the request is sent again:
Failing to connect to the proxy, or to open a tunnel through it: retried for any HTTP method, because the request never reached the target.
Any other connection error or timeout, such as a proxy that drops the connection or stops responding: retried for
GET,HEADandOPTIONSonly. Other methods may already have been acted on, so the error is raised instead.A
407 Proxy Authentication Requiredresponse, or any status you list inretry_statuses: retried for any method.
Anything else, including ordinary error statuses such as 404 or 500, is returned or raised exactly as
requestswould. A TLS error is raised without blaming the proxy, since it usually comes from the target. A slow target cannot be told apart from a slow proxy, so a read timeout counts against the proxy. Deciding that a response means βbannedβ is left to you: list statuses inretry_statusesor callreport_failureyourself.A request made with an explicit
proxies=argument is sent as given, with no rotation. Requests that upload files or stream their body are sent once and never retried, since the body cannot be read twice.- Parameters:
provider β Where proxies come from
algorithm β Selection algorithm, as for
provider.get_proxy(). Defaults to the providerβs round robin.max_retries β How many more proxies to try after the first one fails
retry_statuses β Extra response status codes treated as a failed proxy, e.g.
{403, 429}for a target that blocks proxies. 407 is always included.
Example:
from proxyproviders import Webshare from proxyproviders.session import RotatingSession session = RotatingSession(Webshare(api_key="your-api-key"), max_retries=3) response = session.get("https://httpbin.org/ip", timeout=10) print(response.json(), session.last_proxy)
- last_proxy: Proxy | Noneο
The proxy used for the most recent request, whether it succeeded or not.
Rotating httpx Transportsο
Opt-in httpx transports that pick a proxy for every request, sync and async.
Nothing else in the package uses this module, and it is the only one that needs httpx:
pip install "proxyproviders[httpx]".
- class proxyproviders.httpx_transport.RotatingTransport(*args: Any, **kwargs: Any)[source]ο
Bases:
_Rotation,BaseTransportAn httpx transport that routes each request through a proxy from a provider.
Every request asks the provider for a proxy. If the request fails to get through, the proxy is reported with
report_failure()and the request is sent again through the next one, up tomax_retriesmore times.What counts as a failed proxy:
a connect error, connect timeout or proxy error: retried for any HTTP method, because the request never reached the target
a read or write error or timeout, or a broken response: retried for
GET,HEADandOPTIONSonlya
407 Proxy Authentication Requiredresponse, or any status you list inretry_statuses: retried for any method
Anything else is returned or raised exactly as httpx would. httpx reports a failed TLS handshake with the target as a connect error, so that also counts against the proxy. Requests with a streamed or multipart body are sent once and not retried. One connection pool is kept per proxy used, so connections are reused when a proxy comes round again.
- Parameters:
provider β Where proxies come from
algorithm β Selection algorithm, as for
provider.get_proxy()max_retries β How many more proxies to try after the first one fails
retry_statuses β Extra response status codes treated as a failed proxy, e.g.
{403, 429}. 407 is always included.transport_options β Passed to each underlying
httpx.HTTPTransport, e.g.verify=orhttp2=True
Example:
import httpx from proxyproviders import Webshare from proxyproviders.httpx_transport import RotatingTransport transport = RotatingTransport(Webshare(api_key="your-api-key"), max_retries=3) with httpx.Client(transport=transport) as client: response = client.get("https://httpbin.org/ip")
- class proxyproviders.httpx_transport.AsyncRotatingTransport(*args: Any, **kwargs: Any)[source]ο
Bases:
_Rotation,AsyncBaseTransportThe async version of
RotatingTransport, forhttpx.AsyncClient.It behaves the same way and takes the same arguments. Asking the provider for a proxy runs in a worker thread, so a provider refreshing its list from the vendorβs API does not block the event loop.
Example:
import httpx from proxyproviders import Webshare from proxyproviders.httpx_transport import AsyncRotatingTransport transport = AsyncRotatingTransport(Webshare(api_key="your-api-key")) async with httpx.AsyncClient(transport=transport) as client: response = await client.get("https://httpbin.org/ip")
ProxyProviders Modelsο
- class proxyproviders.models.proxy.Proxy(id: str, username: str, password: str, proxy_address: str, port: int, country_code: str | None = None, city_name: str | None = None, created_at: datetime | None = None, protocols: List[str] | None = None)[source]ο
Bases:
objectOur shared data model for a proxy object across all providers.
- id: strο
A unique identifier for the proxy
- username: strο
The username required for authenticating with the proxy
- password: strο
The password required for authenticating with the proxy. Left out of
repr()so printing or logging a proxy does not expose it.
- proxy_address: strο
The IP address or domain name of the proxy
- port: intο
The port number through which the proxy connection is established
- country_code: str | None = Noneο
The country code where the proxy is located, e.g., βUSβ, βFRβ. Optional
- city_name: str | None = Noneο
The city name where the proxy is located, e.g., βNew Yorkβ, βParisβ. Optional
- created_at: datetime | None = Noneο
The timestamp when the proxy was created. Optional
- protocols: List[str] | None = Noneο
A list of connection protocols supported by the proxy, e.g., [βhttpβ, βhttpsβ]
- classmethod from_string(text: str, id: str | None = None, **fields: Any) Proxy[source]ο
Build a proxy from text, for proxies you already have as a list or a file.
Accepted forms:
a URL:
http://user:pass@host:port,socks5://host:portuser:pass@host:portandhost:port(treated as http)host:port:user:pass, the line format many providers export
- Parameters:
text β The proxy to parse
id β Identifier for the proxy. Defaults to
host:port.fields β Any other
Proxyfields to set, e.g.country_code="US"
- Raises:
ValueError β If the text is not one of the accepted forms
Example
>>> Proxy.from_string("203.0.113.7:8080:user:pass").to_url() 'http://user:pass@203.0.113.7:8080'
- classmethod from_url(url: str, id: str | None = None, **fields: Any) Proxy[source]ο
Build a proxy from a URL such as
http://user:pass@host:port.The reverse of
to_url(): percent-encoded credentials are decoded. Seefrom_string(), which this is an alias of, for every accepted form.
- property scheme: strο
The URL scheme used to connect to this proxy.
protocolslists what the proxy supports. A proxy that supportshttporhttps(or does not say) is reached overhttp. A SOCKS-only proxy, e.g.protocols=["socks5"], is reached over that SOCKS scheme.
- to_url(protocol: str | None = None) str[source]ο
Convert proxy to URL format for use with HTTP clients.
- Parameters:
protocol β The protocol to use in the URL. Defaults to
scheme, which ishttpunless the proxy only supports SOCKS.- Returns:
Proxy URL in format βprotocol://username:password@host:portβ. The username and password are percent-encoded, so characters such as
@,:,#or/in them do not change where the URL points. A proxy with no username and no password gives βprotocol://host:portβ.
Example
>>> proxy.to_url() 'http://user:pass@192.168.1.1:8080' >>> proxy.to_url('https') 'https://user:pass@192.168.1.1:8080'
- format(format_type: Literal[ProxyFormat.URL, ProxyFormat.HTTPX, ProxyFormat.AIOHTTP, ProxyFormat.SCRAPY, ProxyFormat.HOST_PORT_USER_PASS, 'url', 'httpx', 'aiohttp', 'scrapy', 'host_port_user_pass'] = ProxyFormat.URL, **kwargs: Any) str[source]ο
- format(format_type: Literal[ProxyFormat.REQUESTS, ProxyFormat.URLLIB, ProxyFormat.PLAYWRIGHT, ProxyFormat.ENV, 'requests', 'urllib', 'playwright', 'env'], **kwargs: Any) Dict[str, str]
- format(format_type: Literal[ProxyFormat.CURL, 'curl'], **kwargs: Any) List[str]
- format(format_type: ProxyFormat | str, **kwargs: Any) str | Dict[str, str] | List[str]
Format proxy for different HTTP clients and tools.
A SOCKS-only proxy (
protocols=["socks5"]) is formatted with its SOCKS scheme. Your HTTP client needs SOCKS support for that:requests[socks]orhttpx[socks]. aiohttp and Scrapy have no built-in SOCKS support.- Parameters:
format_type β Output format (default: URL string). See
ProxyFormatfor every format and what it is passed to.kwargs β Format-specific options:
protocolforURLandPLAYWRIGHT,protocolsforREQUESTSandURLLIB
- Returns:
Formatted proxy data
Examples
>>> proxy.format() # Default URL string 'http://user:pass@192.168.1.1:8080'
>>> proxy.format(ProxyFormat.REQUESTS) # requests.get(url, proxies=...) {'http': 'http://user:pass@192.168.1.1:8080', 'https': 'http://user:pass@192.168.1.1:8080'}
>>> proxy.format('curl') # String also works ['-x', 'http://user:pass@192.168.1.1:8080']
>>> proxy.format(ProxyFormat.HTTPX) # httpx.Client(proxy=...) 'http://user:pass@192.168.1.1:8080'
>>> proxy.format(ProxyFormat.PLAYWRIGHT) # browser.new_context(proxy=...) {'server': 'http://192.168.1.1:8080', 'username': 'user', 'password': 'pass'}
>>> proxy.format(ProxyFormat.HOST_PORT_USER_PASS) '192.168.1.1:8080:user:pass'
- class proxyproviders.models.proxy.ProxyFormat(*values)[source]ο
Bases:
EnumSupported proxy output formats.
- REQUESTS = 'requests'ο
{"http": url, "https": url}for theproxies=argument of requests
- CURL = 'curl'ο
["-x", url]arguments for the curl command line
- HTTPX = 'httpx'ο
URL string for the
proxy=argument ofhttpx.Client/httpx.AsyncClient
- AIOHTTP = 'aiohttp'ο
URL string for the
proxy=argument of aiohttp requests and sessions
- PLAYWRIGHT = 'playwright'ο
{"server", "username", "password"}for theproxy=option of Playwright
- URL = 'url'ο
scheme://username:password@host:portURL string
- SCRAPY = 'scrapy'ο
URL string for
Request(meta={"proxy": ...})in Scrapy
- URLLIB = 'urllib'ο
{"http": url, "https": url}forurllib.request.ProxyHandler
- ENV = 'env'ο
HTTP_PROXY/HTTPS_PROXY(andALL_PROXYfor SOCKS) environment variables, in upper and lower case, for subprocesses and tools that read them
- HOST_PORT_USER_PASS = 'host_port_user_pass'ο
host:port:username:password, the plain-text line many proxy tools import
Proxy Formatsο
Converters between Proxy and the shapes that HTTP
clients, browsers and tools expect.
Each output format is one small function registered in _FORMATTERS. Adding a format
means adding a ProxyFormat member and a function here; nothing else changes.
Parsing the other way (text to proxy fields) lives in parse_proxy_string().
- class proxyproviders.models.formats.ProxyFormat(*values)[source]ο
Bases:
EnumSupported proxy output formats.
- REQUESTS = 'requests'ο
{"http": url, "https": url}for theproxies=argument of requests
- CURL = 'curl'ο
["-x", url]arguments for the curl command line
- HTTPX = 'httpx'ο
URL string for the
proxy=argument ofhttpx.Client/httpx.AsyncClient
- AIOHTTP = 'aiohttp'ο
URL string for the
proxy=argument of aiohttp requests and sessions
- PLAYWRIGHT = 'playwright'ο
{"server", "username", "password"}for theproxy=option of Playwright
- URL = 'url'ο
scheme://username:password@host:portURL string
- SCRAPY = 'scrapy'ο
URL string for
Request(meta={"proxy": ...})in Scrapy
- URLLIB = 'urllib'ο
{"http": url, "https": url}forurllib.request.ProxyHandler
- ENV = 'env'ο
HTTP_PROXY/HTTPS_PROXY(andALL_PROXYfor SOCKS) environment variables, in upper and lower case, for subprocesses and tools that read them
- HOST_PORT_USER_PASS = 'host_port_user_pass'ο
host:port:username:password, the plain-text line many proxy tools import
- proxyproviders.models.formats.format_proxy(proxy: Proxy, format_type: ProxyFormat | str, **kwargs: Any) str | Dict[str, str] | List[str][source]ο
Format
proxyasformat_type. SeeProxy.format().
- proxyproviders.models.formats.parse_proxy_string(text: str) Dict[str, Any][source]ο
Parse one proxy written as text into the fields of a
Proxy.Accepted forms:
a URL:
http://user:pass@host:port,socks5://host:porthost:port:user:pass, the line format many providers export, andhost:portuser:pass@host:port(treated as http)
Percent-encoded credentials in a URL are decoded. In
host:port:user:passthe password is everything after the third colon, so it may itself contain:or@. An IPv6 host is written in square brackets, e.g.[2001:db8::1]:8080.- Raises:
ValueError β if the text is not one of these forms
ProxyProviders Exceptionsο
All custom exceptions for the ProxyProvider classes are defined here.
- exception proxyproviders.exceptions.ProxyProviderException[source]ο
Bases:
ExceptionBase class for all ProxyProvider errors.
- exception proxyproviders.exceptions.ProxyFetchException(message: str, status_code: int | None = None)[source]ο
Bases:
ProxyProviderExceptionRaised when there is an error fetching proxies from the provider.
- exception proxyproviders.exceptions.ProxyConversionException[source]ο
Bases:
ProxyProviderExceptionRaised when there is an error converting proxy data to a standardized format.
- exception proxyproviders.exceptions.ProxyInvalidResponseException(response: str)[source]ο
Bases:
ProxyProviderExceptionRaised when the provider returns an invalid response.