BeautifulSoup with Proxies: Python Web Scraping Setup

BeautifulSoup is a Python library for parsing HTML, but you need a separate library like `requests` to fetch web pages through a proxy. This guide shows you how to configure RotatingProxy's gateway with `requests` to scrape reliably, manage sessions, and handle common errors. You'll learn to pass targeting options in the username and verify your exit IP.

Key points
  • Use the `requests` library with the `proxies` parameter to route traffic through the gateway.
  • Build the proxy username with options like network, country, and session ID.
  • Add delays and respect robots.txt to scrape politely and avoid blocks.
  • Verify the proxy is working by checking the exit IP against an IP API.

BeautifulSoup with Proxies: The Core Setup

BeautifulSoup itself does not fetch web pages; it only parses HTML. To use BeautifulSoup with proxies, you pair it with a fetching library like Python's requests. The proxy configuration is applied within the fetching library, which sends the HTTP request through the RotatingProxy gateway. The gateway then routes your request through a rotating IP from your chosen network, fetches the page, and returns the HTML to your script. BeautifulSoup can then parse that HTML as usual. This separation is key: the proxy handles the network layer, while BeautifulSoup handles the document structure.

Where to Put Proxy Settings in Python

Proxy settings for requests are passed in a dictionary to the proxies parameter of the get() or post() method. This dictionary defines the proxy URL for HTTP and HTTPS protocols. The URL contains the gateway host, port, and your login details. You typically set this up once in your script and reuse it for multiple requests. For more advanced scenarios like asynchronous scraping, the setup differs, but the core principle of providing a proxy URL remains the same.

HTTP and HTTPS Setup on Port 7070

Use port 7070 for HTTP and HTTPS traffic via the HTTP CONNECT method. Here is the exact code to configure requests with your RotatingProxy credentials. Replace USERNAME and PASSWORD with your proxy user's login and password, and add any targeting options to the username as shown.

import requests
from bs4 import BeautifulSoup

# Your proxy credentials and options
proxy_login = "USERNAME"
proxy_password = "PASSWORD"
proxy_host = "gw.rotatingproxy.cc"
proxy_port = 7070

# Construct the proxy URL with authentication
proxy_url = f"http://{proxy_login}:{proxy_password}@{proxy_host}:{proxy_port}"

# Define the proxies dictionary for requests
proxies = {
    "http": proxy_url,
    "https": proxy_url,
}

# Make a request through the proxy
try:
    response = requests.get("https://httpbin.org/ip", proxies=proxies, timeout=30)
    response.raise_for_status()  # Raise an exception for bad status codes
    print(f"Proxy response: {response.text}")

    # Now parse content with BeautifulSoup if needed
    # soup = BeautifulSoup(response.content, 'html.parser')
except requests.exceptions.RequestException as e:
    print(f"Request failed: {e}")

This configuration routes both HTTP and HTTPS traffic through the same gateway. The requests library automatically uses the HTTP CONNECT method for HTTPS URLs, which is fully supported on port 7070.

SOCKS5 Setup on Port 7071

BeautifulSoup with requests can also use the SOCKS5 proxy on port 7071, but it requires an extra library. The standard requests library does not natively support SOCKS. You must install requests[socks] or the PySocks package. If you cannot install additional packages, stick with port 7070. Here is the setup if SOCKS5 is needed for your toolchain:

pip install requests[socks]
import requests
from bs4 import BeautifulSoup

proxy_login = "USERNAME"
proxy_password = "PASSWORD"
proxy_host = "gw.rotatingproxy.cc"
proxy_port = 7071

proxy_url = f"socks5://{proxy_login}:{proxy_password}@{proxy_host}:{proxy_port}"

proxies = {
    "http": proxy_url,
    "https": proxy_url,
}

response = requests.get("https://api.ipify.org", proxies=proxies, timeout=30)
print(response.text)

For most web scraping work, the HTTP proxy on port 7070 is enough and easier. Only use SOCKS5 if your target app or network setup specifically needs it. Learn more about the differences in our guide on HTTP vs SOCKS5 proxies.

Passing Targeting and Session Options in the Username

You control the network, location, and session behavior by appending options to the proxy username, separated by underscores. The basic format is login_key1.value1_key2.value2. For example, to use a mobile IP from Germany with a specific city and a sticky session, you would construct the username like this:

base_login = "zq4k8m2tva"  # Your proxy user login
options = "_net.mob_cc.de_city.berlin_sid.a7k2m9_ttl.20"
proxy_login = base_login + options
# proxy_login becomes: zq4k8m2tva_net.mob_cc.de_city.berlin_sid.a7k2m9_ttl.20

Key options include:

  • net.res, net.mob, net.dc, net.isp: Choose the proxy network. The default is net.res (residential).
  • cc.us: Target a country using its lowercase ISO code (e.g., cc.fr for France).
  • st.ca: Target a US state (only works with cc.us).
  • city.new-york: Target a city from our published list. Use hyphens for spaces.
  • sid.abc123: Set a session ID (6-16 chars). This creates a sticky session, keeping the same IP for the TTL period.
  • ttl.30: Set the sticky session lifetime in minutes (1-120). Default is 10 when sid is set.

To get a new IP on every connection, simply omit the sid option. For detailed examples, see our username options documentation.

Verifying the Exit IP and Location

Always verify that your proxy is working and showing the expected IP and location. Use a simple IP checking service within your script. This confirms authentication succeeded and the targeting options are applied.

import requests
import json

proxies = { "http": proxy_url, "https": proxy_url }  # Your proxy_url from earlier

# Option 1: Simple IP
resp = requests.get("https://api.ipify.org?format=json", proxies=proxies, timeout=10)
print(f"Exit IP: {resp.json()['ip']}")

# Option 2: Detailed location (useful for geo-targeting checks)
resp = requests.get("https://ipinfo.io/json", proxies=proxies, timeout=10)
data = resp.json()
print(f"IP: {data['ip']}, Country: {data.get('country')}, City: {data.get('city')}")

If the IP or location does not match your targeting, double-check the username string for typos. Also, ensure your proxy user in the dashboard is allowed to use the selected network. For more tools, visit our IP check tools guide.

Common Proxy Errors and Fixes

When using BeautifulSoup with proxies, you might encounter these common errors in the fetching stage.

407 Proxy Authentication Required

This shows the proxy gateway did not accept your login details. Check that the username and password in the proxy URL are correct, including any targeting options. Ensure the proxy user is not paused and has available balance. For a dedicated guide, see solving error 407.

Connection Timeouts

Timeouts can occur if the target site is slow or the proxy exit node has high latency. Increase the timeout parameter in your requests.get() call (e.g., timeout=30). Add a retry system with exponential backoff. Also, consider switching to a different proxy network; for example, datacenter or ISP proxies often have lower latency than residential.

TLS/SSL Certificate Errors

When connecting to HTTPS sites through the proxy, you might see SSL errors. This is often due to the target site's certificate or an intermediate inspection. You can bypass this for testing by passing verify=False to requests.get(), but this is insecure for production. A better approach is to ensure your system's CA certificates are up to date.

Target Site Returns 403 Forbidden

This indicates the target site blocked the request, not the proxy. The IP may have a poor reputation or the request lacked typical browser headers. Always set a realistic User-Agent header. Rotate user agents and other headers between requests. Using polite scraping practices is essential.

Tips for Running at Scale with BeautifulSoup

When scraping many pages, efficiency and cost management become critical.

  • Use Sessions: The requests.Session() object can reuse the underlying TCP connection to the proxy gateway, reducing overhead. You still need to pass the proxies dictionary to the session.
  • Implement Polite Delays: Add random delays between requests using time.sleep() to avoid overwhelming target sites and triggering rate limits. This also helps your proxy IPs last longer.
  • Respect robots.txt: Check the target site's robots.txt file and honor its directives. Our guide on reading robots.txt explains how.
  • Cache Responses: If you need to re-parse the same page, cache the HTML locally to avoid repeated proxy traffic and costs. Learn about saving bandwidth.
  • Monitor Traffic: Keep an eye on your usage in the dashboard to avoid unexpected costs. Use the traffic calculator to estimate needs for projects like price monitoring or rank tracking.
  • Handle Concurrency: You can open many concurrent connections through the proxy (up to 1,000 per account). Use a thread pool or an async library like aiohttp for parallel requests.

Example: Complete Scraper with Proxy and BeautifulSoup

Here is a complete, polite example that fetches a page, parses it with BeautifulSoup, and includes error handling and delays.

import requests
from bs4 import BeautifulSoup
import time
import random

def scrape_with_proxy(url, proxy_url):
    proxies = {"http": proxy_url, "https": proxy_url}
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
    }
    try:
        # Add a random delay between 1 and 3 seconds
        time.sleep(random.uniform(1, 3))
        resp = requests.get(url, headers=headers, proxies=proxies, timeout=30)
        resp.raise_for_status()
        return BeautifulSoup(resp.content, 'html.parser')
    except requests.exceptions.HTTPError as e:
        print(f"HTTP error for {url}: {e}")
    except requests.exceptions.Timeout:
        print(f"Timeout for {url}")
    except requests.exceptions.RequestException as e:
        print(f"Request failed for {url}: {e}")
    return None

# Your proxy URL
proxy_url = "http://USERNAME_net.res_cc.us:PASSWORD@gw.rotatingproxy.cc:7070"

# Example usage
soup = scrape_with_proxy("https://example.com/products", proxy_url)
if soup:
    product_titles = soup.find_all('h2', class_='product-title')
    for title in product_titles:
        print(title.get_text(strip=True))

This pattern is adaptable for many web scraping use cases, from Google Shopping data to job listings.

Next Steps and Integration

For large-scale scraping projects, consider using a framework like Scrapy which has built-in proxy middleware. If you need to render JavaScript, pair proxies with Playwright or Selenium. Always start by checking if the site offers a public API to reduce load. Understand your costs with our pay-as-you-go billing explanation and the volume rates. Finally, ensure your activities comply with our acceptable use policy and respect website terms.

Questions

Can I use BeautifulSoup with asynchronous requests and proxies?

Yes, but you need an async HTTP client like `aiohttp` or `httpx`. BeautifulSoup remains the parser for the HTML you fetch. The proxy configuration is set in the async client's connection parameters, similar to the `requests` library. Check the current docs for your chosen async library, as the syntax differs.

Why is my BeautifulSoup script getting blocked even with a proxy?

Proxies rotate IPs, but sites use other signals to block bots: HTTP headers, request rate, mouse movements, and TLS fingerprints. Ensure you set common browser headers (User-Agent, Accept), add delays between requests, and consider using a headless browser for JavaScript-heavy sites. Review our guide on avoiding IP bans politely.

How do I scrape a site that requires login with BeautifulSoup and proxies?

Use a `requests.Session()` to persist cookies across requests. First, POST your login credentials through the proxy to the site's login endpoint, then use the same session to access protected pages. The session will automatically handle cookies, and all traffic will route through the proxy defined in the session's `proxies` attribute.

Does RotatingProxy support IPv6 for BeautifulSoup scraping?

No, the gateway provides IPv4 exits only. Your requests library will connect to the gateway using IPv4. The target site will see an IPv4 address from our pool. This is sufficient for the vast majority of web scraping tasks.

How can I reduce proxy traffic costs when using BeautifulSoup?

Cache responses locally, compress responses if the server supports it (use `gzip` in headers), and only download necessary pages. Avoid downloading large assets like images or videos unless needed. Also, set a monthly GB cap on your proxy user in the dashboard. Learn more in how to reduce proxy traffic costs.

My script works without a proxy but fails with one. What should I check?

First, verify the proxy connection is alive by fetching a simple IP check URL. If that works, the issue is likely with your request configuration for the target site. Compare the headers and TLS fingerprint of a request made directly versus through the proxy. Some sites block known proxy IP ranges. Try switching to a different network, like mobile proxies, which often have better reputations for certain targets.

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.