aiohttp proxy: async Python scraping with rotating IPs

You can route aiohttp requests through RotatingProxy by setting the proxy parameter in a ClientSession. Connect using port 7070 for HTTP/HTTPS or port 7071 for SOCKS5. Targeting and session control are passed via the proxy username.

Key points
  • Use `proxy='http://USERNAME:PASSWORD@gw.rotatingproxy.cc:7070'` in ClientSession.
  • SOCKS5 requires the `aiohttp-socks` package and port 7071.
  • Embed options like `cc.us` or `sid.abc123` in the username.
  • Control concurrency with semaphores and connection limits.

aiohttp proxy settings location

The proxy is configured when you create an aiohttp.ClientSession. You pass the proxy URL as a string to the proxy keyword argument. This setting applies to all requests made through that session unless overridden at the request level. For SOCKS5 support, you need to install the aiohttp-socks library and use a different session connector.

HTTP and HTTPS proxy on port 7070

For HTTP and HTTPS traffic, use our gateway host gw.rotatingproxy.cc on port 7070. The proxy URL includes your proxy user's login, password, and any targeting options appended to the username. Here is a basic async function that creates a session and makes a request:

import aiohttp
import asyncio

async def fetch_with_proxy():
    proxy_auth = aiohttp.BasicAuth('USERNAME_net.res_cc.us', 'PASSWORD')
    async with aiohttp.ClientSession(
        proxy='http://gw.rotatingproxy.cc:7070',
        proxy_auth=proxy_auth
    ) as session:
        async with session.get('https://httpbin.org/ip') as resp:
            print(await resp.text())

asyncio.run(fetch_with_proxy())

Note that the targeting options net.res and cc.us are part of the username string. HTTPS requests (CONNECT) work transparently through the same proxy URL.

SOCKS5 proxy on port 7071 with aiohttp-socks

aiohttp does not natively support SOCKS5 proxies. To use our SOCKS5 port 7071, install the aiohttp-socks package (pip install aiohttp-socks). You then create a custom connector and pass it to the session. This is useful if your target environment works better with SOCKS5 or you are integrating with other tools that prefer SOCKS.

import aiohttp
import aiohttp_socks
import asyncio

async def fetch_with_socks5():
    connector = aiohttp_socks.ProxyConnector.from_url(
        'socks5://USERNAME_net.mob_cc.de:PASSWORD@gw.rotatingproxy.cc:7071'
    )
    async with aiohttp.ClientSession(connector=connector) as session:
        async with session.get('https://api.ipify.org') as resp:
            print(await resp.text())

asyncio.run(fetch_with_socks5())

The connector handles all authentication and protocol details. Remember that the username still contains the network and country options. For a comparison of when to use each port, see our guide on HTTP port vs SOCKS5 port.

Passing targeting and session options in the username

All geo-targeting and session control is done through the proxy username. You build a string that starts with your proxy user's login, followed by underscores and key.value pairs. For example, to target Chicago with a sticky session for 30 minutes, you would use:

username = 'USERNAME_net.res_cc.us_city.chicago_sid.myappk_ttl.30'
password = 'PASSWORD'
proxy_url = f'http://{username}:{password}@gw.rotatingproxy.cc:7070'

The options are processed left to right, so place the network (net.res, net.mob, net.dc, or net.isp) first for clarity.

Verifying the exit IP and location

After setting up the proxy, you should verify that requests are exiting from the expected IP and location. A simple async check can use a service like ipify or ipinfo.

async def check_ip(session):
    async with session.get('https://api.ipify.org?format=json') as resp:
        data = await resp.json()
        print(f"Exit IP: {data['ip']}")
    # For location details
    async with session.get('https://ipinfo.io/json') as resp:
        details = await resp.json()
        print(f"Country: {details.get('country')}, City: {details.get('city')}")

Run this check at the start of your scraper to ensure proper configuration. If the IP doesn't match your targeting, double-check the username options and that your proxy user is allowed on the chosen network. More tools for this are listed in our IP check tools guide.

Common proxy errors and fixes in aiohttp

When using aiohttp with proxies, you may encounter specific errors.

407 Proxy Authentication Required

Check that the username and password are correct and URL-encoded properly (aiohttp's BasicAuth does this). Ensure the proxy user is not paused and has access to the network specified in the username. For more, see proxy error 407.

Timeout errors and slow responses

Timeouts can occur if the target site is slow or if your concurrency is too high for the proxy gateway. Increase the timeout on your session or request level. Also, consider using a different network; for example, datacenter proxies often have lower latency than residential. We cover this topic thoroughly in our retry strategies for proxy requests guide.

TLS/SSL errors with HTTPS

If you see SSL certificate errors, ensure you are not validating the proxy's certificate. You can create a custom TCPConnector with ssl=False, but note this reduces security. A better approach is to use the default SSL context and let aiohttp handle the CONNECT tunnel, which it does automatically when using the proxy parameter.

Running aiohttp at scale with concurrency control

For large-scale async crawling, you need to manage concurrency to avoid overwhelming your own system or the proxy gateway. Use asyncio semaphores to limit the number of concurrent requests. Also, configure the aiohttp TCPConnector to limit total connections and per-host connections.

async def bound_fetch(sem, session, url):
    async with sem:
        async with session.get(url) as response:
            return await response.text()

async def main(urls):
    connector = aiohttp.TCPConnector(limit=100, limit_per_host=20)
    proxy_auth = aiohttp.BasicAuth('USERNAME_net.dc', 'PASSWORD')
    async with aiohttp.ClientSession(
        connector=connector,
        proxy='http://gw.rotatingproxy.cc:7070',
        proxy_auth=proxy_auth
    ) as session:
        sem = asyncio.Semaphore(50)  # 50 concurrent requests max
        tasks = [bound_fetch(sem, session, url) for url in urls]
        await asyncio.gather(*tasks)

This setup ensures you stay within the account's concurrency limit of 1,000 connections. Adjust the semaphore and connector limits based on your hardware and the target site's tolerance. For planning, read planning concurrency for crawlers.

Using sticky sessions for login flows

When you need to maintain the same IP across multiple requests, such as for logging into a site or maintaining a shopping cart, use a sticky session. Include a sid (session ID) and a ttl (time-to-live in minutes) in the username. The same IP will be assigned for that session ID for the duration of the TTL, as long as you keep using the same username string.

session_id = 'mycart123'
username = f'USERNAME_net.res_sid.{session_id}_ttl.45'
# Use this username for all requests in the same logical session

If the IP changes before the TTL expires, it could be because the device behind the IP went offline. The system will automatically move you to a new IP in the same location. Details are in the how to keep the same IP guide.

Reducing proxy traffic and costs

Since billing is pay as you go per GB, optimizing bandwidth saves money. Use HTTP compression by setting the Accept-Encoding header. Consider using datacenter proxies for high-volume tasks where residential IPs aren't required, as they have lower entry rates. Also, monitor your monthly volume to benefit from automatic volume rate discounts.

Integrating with scraping frameworks

While aiohttp is powerful for custom async crawlers, you might also integrate it with higher-level frameworks. For example, you can use aiohttp as the downloader for Scrapy by customizing the downloader handlers. Similarly, for price monitoring or rank tracking, you can wrap aiohttp sessions in a task scheduler. If you prefer a more out-of-the-box solution, check our integration guides for Scrapy proxy and Playwright Python proxy.

Best practices for async scraping with proxies

Follow the directives in robots.txt and the site's terms. Implement polite crawling by adding delays between requests to the same domain. Rotate user agents along with IPs to reduce fingerprinting. Use a solid error handling and retry mechanism, as network errors are more common when using proxies. For a comprehensive list, see our web scraping best practices. Also, ensure your use case aligns with our acceptable use policy.

Monitoring usage and balance

Keep an eye on your balance and traffic consumption through the dashboard or via the REST API. Set up alerts in your code to stop before the balance runs out. You can also assign monthly GB caps to individual proxy users to prevent unexpected overuse. If you're running a large project, estimate your needs with our traffic calculator.

Questions

Can I use aiohttp with RotatingProxy for scraping Google Search?

Yes, you can target the appropriate country and use residential or mobile proxies. Ensure you comply with Google's terms and implement respectful delays. See our dedicated guide for Google search proxies.

What happens if my balance reaches zero during a long-running aiohttp task?

The proxy gateway will stop forwarding traffic, and your requests will likely time out or return connection errors. You should monitor your balance and top up before it runs out. After a top-up, traffic resumes automatically.

How can I change the IP for every request in aiohttp?

Do not include a <code>sid</code> option in the username. Each new connection through the gateway will receive a new IP. You can also create a new ClientSession for each request, but reusing a session without a session ID will still rotate IPs per connection.

My aiohttp script works without proxy but fails with a timeout when using the proxy. What should I check?

First, verify the proxy connection with a simple IP check. If that works, the timeout may be due to the target site blocking the proxy IP. Try a different network (e.g., switch from datacenter to residential) or increase the timeout value in your session or request.

Does aiohttp resolve DNS through the proxy?

When using the HTTP proxy (port 7070), DNS resolution happens on the proxy exit node, preventing DNS leaks. With the SOCKS5 connector from <code>aiohttp-socks</code>, DNS can be configured to be remote (proxy-resolved) or local; check the current docs for the connector options.

Can I use the same aiohttp session for requests to different countries?

No, the geo-targeting is embedded in the proxy username used for the session's authentication. To switch countries, you need to create a new session with a different username (or override the proxy auth at the request level, which is more complex).

Start with one top-up, use any network

Create an account in a minute, add $40 or more, and the same balance pays for residential, mobile, datacenter and ISP traffic.