ProxyForge Download

How to Avoid IP Bans When Scraping: 7 Proven Techniques

Introduction

Web scraping is an essential tool for gathering data from websites. However, one of the biggest challenges you'll face is avoiding IP bans. Websites have various mechanisms to detect and block automated traffic, including rate limiting, IP blacklisting, CAPTCHAs, and more. In this guide, we will explore seven proven techniques to help you avoid IP bans while scraping.

1. Rate Limiting

Rate limiting is the most common method websites use to prevent scrapers from overwhelming their servers. By controlling how often your requests are sent, you can reduce the risk of being detected and banned.

a. Implement Delays Between Requests

The simplest way to implement rate limiting is by adding delays between your HTTP requests. This mimics human behavior and reduces the load on the target website.

import time
import requests

def fetch_url(url):
    response = requests.get(url)
    return response.text

urls = ['http://example.com', 'http://another-example.com']

for url in urls:
    print(fetch_url(url))
    time.sleep(2)  # Sleep for 2 seconds between requests

b. Use an Exponential Backoff Algorithm

An exponential backoff algorithm increases the delay after each failed request, making your scraper more resilient to temporary server issues.

import random
import time
import requests

def fetch_url(url):
    retries = 5
    delay = 1

    while retries > 0:
        try:
            response = requests.get(url)
            return response.text
        except requests.RequestException as e:
            print(f"Request failed: {e}, retrying in {delay} seconds...")
            time.sleep(delay)
            delay *= 2
            retries -= 1

    raise Exception("Failed to fetch URL after multiple attempts")

2. Proxy Rotation

Using proxies is one of the most effective ways to avoid IP bans. By rotating through a list of proxies, you can distribute your traffic across different IPs and reduce the risk of being detected.

a. Create a Proxy Pool

First, create a pool of proxy servers that you will use in your scraper.

proxies = [
    'http://proxy1.example.com:8080',
    'http://proxy2.example.com:8080',
    # Add more proxies as needed
]

b. Rotate Proxies in Your Requests

Use a proxy from the pool for each request.

import random
import requests

def fetch_url_with_proxy(url, proxies):
    proxy = random.choice(proxies)
    try:
        response = requests.get(url, proxies={"http": proxy, "https": proxy})
        return response.text
    except requests.RequestException as e:
        print(f"Request failed with proxy {proxy}: {e}")
        return None

urls = ['http://example.com', 'http://another-example.com']

for url in urls:
    content = fetch_url_with_proxy(url, proxies)
    if content:
        print(content)

3. Manage Headers and User Agents

Headers and user agents can help mask your scraper as a legitimate browser request.

a. Set Realistic Headers

Set headers like User-Agent to mimic real browser requests.

import requests

headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.131 Safari/537.36',
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
    'Accept-Language': 'en-US,en;q=0.5'
}

def fetch_url_with_headers(url):
    response = requests.get(url, headers=headers)
    return response.text

url = 'http://example.com'
print(fetch_url_with_headers(url))

b. Randomize User Agents

Randomizing user agents can help avoid detection by making your scraper appear less predictable.

import random
import requests

user_agents = [
    'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.131 Safari/537.36',
    'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.0.2 Safari/605.1.15',
    # Add more user agents as needed
]

def fetch_url_with_random_user_agent(url):
    headers = {
        'User-Agent': random.choice(user_agents),
        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
        'Accept-Language': 'en-US,en;q=0.5'
    }
    response = requests.get(url, headers=headers)
    return response.text

url = 'http://example.com'
print(fetch_url_with_random_user_agent(url))

4. Handle CAPTCHAs

CAPTCHAs are designed to distinguish between human users and bots. Handling CAPTCHAs can be challenging, but there are several techniques you can use.

a. Use Third-Party Services

Third-party services like 2Captcha or Anti-Captcha offer APIs that solve CAPTCHAs automatically.

import requests

def solve_captcha(api_key, site_key, page_url):
    payload = {
        'key': api_key,
        'method': 'userrecaptcha',
        'googlekey': site_key,
        'pageurl': page_url
    }
    response = requests.post('http://2captcha.com/in.php', data=payload)
    if response.text.startswith('OK|'):
        captcha_id = response.text.split('|')[1]
        while True:
            check_response = requests.get(f'http://2captcha.com/res.php?key={api_key}&action=get&id={captcha_id}')
            if check_response.text == 'CAPTCHA_NOT_READY':
                time.sleep(5)
            elif check_response.text.startswith('OK|'):
                captcha_solution = check_response.text.split('|')[1]
                return captcha_solution
    else:
        raise Exception(f"Failed to submit CAPTCHA: {response.text}")

# Example usage
api_key = 'YOUR_API_KEY'
site_key = 'SITE_KEY_FROM_PAGE'
page_url = 'http://example.com'
captcha_solution = solve_captcha(api_key, site_key, page_url)
print(captcha_solution)

b. Implement CAPTCHA Solving Scripts

If you prefer not to use third-party services, you can implement scripts that interact with CAPTCHAs.

import time
from selenium import webdriver

def solve_captcha_with_selenium(driver, captcha_url):
    driver.get(captcha_url)
    # Add code to interact with the CAPTCHA (e.g., click buttons, type text)
    time.sleep(10)  # Allow time for manual interaction or automation
    return "CAPTCHA_SOLUTION"

# Example usage
driver = webdriver.Chrome()
captcha_solution = solve_captcha_with_selenium(driver, 'http://example.com/captcha')
print(captcha_solution)

5. Monitor and Analyze Responses

Monitoring the responses from your requests can help you detect patterns that indicate your IP has been banned or is under scrutiny.

a. Check HTTP Status Codes

Monitor HTTP status codes to identify errors or redirects that may indicate issues.

import requests

def fetch_url_and_check_status(url):
    response = requests.get(url)
    if response.status_code == 200:
        return response.text
    else:
        print(f"Failed to fetch URL: Status code {response.status_code}")
        return None

url = 'http://example.com'
content = fetch_url_and_check_status(url)
if content:
    print(content)

b. Analyze Response Headers

Inspect response headers for clues about your IP's status.

import requests

def fetch_url_and_analyze_headers(url):
    response = requests.get(url)
    if 'X-Robots-Tag' in response.headers and 'noindex' in response.headers['X-Robots-Tag']:
        print("Robot detection mechanism triggered")
    if 'Set-Cookie' in response.headers and 'captcha' in response.headers['Set-Cookie'].lower():
        print("CAPTCHA challenge detected")
    return response.text

url = 'http://example.com'
content = fetch_url_and_analyze_headers(url)
if content:
    print(content)

Conclusion

Avoiding IP bans when scraping requires a multi-faceted approach. By implementing rate limiting, rotating proxies, managing headers and user agents, handling CAPTCHAs, and monitoring responses, you can significantly reduce the risk of being detected and banned.

If you'd rather not manage proxy lists manually, ProxyForge auto-tests and rotates proxies locally on your machine — one-off $29 unlock, no subscription: https://proxyforge.dev/#download

Free proxies break. ProxyForge doesn't.

The free lists above are public and often unreliable. ProxyForge auto-tests and rotates proxies on your machine, your IP — no stale lists, no shared pools, no surprises. One-off purchase, no subscription.

Download ProxyForge free →