Skip to content

How to Fix Python Web Scraping Being Blocked by Websites

DodaTech 2 min read

In this tutorial, you'll learn about How to Fix Python Web Scraping Being Blocked by Websites. We cover key concepts, practical examples, and best practices.

The Problem

Your Python scraper gets HTTP 403 Forbidden, HTTP 429 Too Many Requests, or receives a CAPTCHA page instead of the expected data. Websites detect non-human traffic by checking for missing or suspicious headers, too-high request rates, known datacenter IP ranges, and abnormal browser behavior patterns. When any of these checks fail, the server blocks the request.

Quick Fix

1. Set a realistic User-Agent and common headers

import requests

session = requests.Session()
session.headers.update({
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
    'Accept-Language': 'en-US,en;q=0.5',
    'Accept-Encoding': 'gzip, deflate, br',
    'Connection': 'keep-alive',
})

response = session.get('https://example.com/data')
print(response.status_code, len(response.content))

Expected output:

200 45230

2. Add random delays between requests

import time
import random

urls = [
    'https://example.com/page/1',
    'https://example.com/page/2',
    'https://example.com/page/3',
]

for url in urls:
    delay = random.uniform(2.0, 5.0)
    print(f'Sleeping {delay:.1f}s before {url}')
    time.sleep(delay)
    response = session.get(url)
    print(f'{url}: {response.status_code}')

3. Rotate user agents and use proxies

from itertools import cycle
import random

user_agents = [
    'Mozilla/5.0 (Windows NT 10.0; Win64; x64) ...Chrome/120',
    'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) ...Safari/605',
    'Mozilla/5.0 (X11; Linux x86_64) ...Firefox/121',
]

proxies = [
    'http://proxy1.example.com:8080',
    'http://proxy2.example.com:8080',
]

proxy_pool = cycle(proxies)

for url in url_list:
    proxy = next(proxy_pool)
    user_agent = random.choice(user_agents)
    response = requests.get(
        url,
        headers={'User-Agent': user_agent},
        proxies={'http': proxy, 'https': proxy},
        timeout=10,
    )

4. Respect robots.txt

from urllib.robotparser import RobotFileParser

rp = RobotFileParser()
rp.set_url('https://example.com/robots.txt')
rp.read()

url = 'https://example.com/data'
if rp.can_fetch('MyScraperBot', url):
    print(f'Allowed to scrape: {url}')
else:
    print(f'Blocked by robots.txt: {url}')

Expected output:

Allowed to scrape: https://example.com/data

5. Use a headless browser for JavaScript-heavy sites

pip install playwright
playwright install chromium
from playwright.sync_api import sync_playwright

with sync_playwright() as p:
    browser = p.chromium.launch(headless=True)
    context = browser.new_context(
        user_agent='Mozilla/5.0 ...Chrome/120',
        viewport={'width': 1280, 'height': 720},
    )
    page = context.new_page()
    page.goto('https://example.com')
    content = page.content()
    print(f'Page loaded, content length: {len(content)}')
    browser.close()

Verify Your Python Environment

python3 --version
# Python 3.10.12
pip list | grep requests
# requests            2.31.0

Check your Python version and installed packages before debugging. Many errors are caused by version mismatches between development and production environments. Using a virtual environment with pinned dependencies prevents these surprises.

Additional Troubleshooting

# Check the error message and stack trace for more context
echo "Review the full error output to identify the root cause"

If the above steps do not resolve the issue, examine the complete error message and stack trace. Often the key detail is in the middle of the traceback rather than the final line. Search for the error message in the project documentation or issue tracker for additional solutions.

Prevention

  • Always check robots.txt first before writing any scraper logic
  • Add a polite time.sleep(random.uniform(1, 5)) between every request
  • Rotate user agents and IP addresses for large-scale scraping operations
  • Use headless browsers only when necessary — they consume more memory and are easier to detect
  • Monitor response status codes and content type to detect when blocking starts, then adjust your strategy

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro