01httpx
Recent versions of httpx take a single proxy= argument (older ones used proxies=). The client is async, so many requests can share it.
import asyncio
import httpx
PROXY = "http://USERNAME:PASSWORD@dc.fullstackproxy.com:38417"
async def main():
async with httpx.AsyncClient(proxy=PROXY, timeout=30) as client:
r = await client.get("https://api.ipify.org?format=json")
print(r.json())
asyncio.run(main())02Many requests at once, with a limit
A semaphore caps how many requests are open at a time. Start around 20 to 50 and raise it while the target keeps answering with 200s.
import asyncio
import httpx
PROXY = "http://USERNAME-country-us:PASSWORD@dc.fullstackproxy.com:38417"
urls = [f"https://example.com/item/{n}" for n in range(1, 201)]
limit = asyncio.Semaphore(32)
async def fetch(client, url):
async with limit:
try:
r = await client.get(url)
return url, r.status_code
except httpx.HTTPError as e:
return url, type(e).__name__
async def main():
async with httpx.AsyncClient(proxy=PROXY, timeout=30) as client:
for url, status in await asyncio.gather(*(fetch(client, u) for u in urls)):
print(status, url)
asyncio.run(main())03aiohttp
aiohttp takes the proxy per request. Put the login in the proxy URL: the separate proxy_auth argument is deprecated in recent versions.
import asyncio
import aiohttp
PROXY = "http://USERNAME-country-de:PASSWORD@gw.fullstackproxy.com:47631"
async def main():
timeout = aiohttp.ClientTimeout(total=30)
async with aiohttp.ClientSession(timeout=timeout) as session:
async with session.get("https://api.ipify.org", proxy=PROXY) as r:
print(await r.text())
asyncio.run(main())04One IP per worker
To keep an IP for a run of requests, give each worker its own client with its own session name. Requests inside that client then share one exit.
async def worker(n, urls):
proxy = f"http://USERNAME-session-w{n}-lifetime-30:PASSWORD@gw.fullstackproxy.com:47631"
async with httpx.AsyncClient(proxy=proxy, timeout=30) as client:
for url in urls:
await client.get(url)