cloudscraper

repository·master·Indexed 27 days ago

https://github.com/venomous/cloudscraper

An enhanced Python module (v3.0.0) designed to bypass Cloudflare's anti-bot protections (IUAM), including v2 and v3 challenges and Turnstile. It provides a Requests-compatible session that supports multiple JavaScript engines (js2py, Node.js, V8, ChakraCore, and native), proxy rotation, stealth mode for human-like behavior, and integration with third-party CAPTCHA solvers such as 2captcha, anticaptcha, and CapSolver.

Tokens
11.6K
Snippets
26
Records
70
Agent score
88%

What's inside cloudscraper

  1. Install or Upgrade cloudscraper to v3.0.0

    master

    To upgrade an existing installation to version 3.0.0 or to perform a fresh installation, use pip.

    Note: Version 3.0.0 requires Python 3.8+.

    # Upgrade to v3.0.0
    pip install --upgrade cloudscraper
    
    # Or install fresh
    pip install cloudscraper>=3.0.0
  2. Migrate from the original cloudscraper package

    master

    If you are migrating from the original cloudscraper package to this enhanced version, the API remains compatible. You only need to update your import statements. All function calls and parameters remain the same.

    # Enhanced import
    import cloudscraper  # Enhanced version
  3. Ensure compatibility when building executables

    master

    When converting your application to an executable using tools like PyInstaller, cx_Freeze, or auto-py-to-exe, cloudscraper includes an automatic fallback system for missing browsers.json files.

    To ensure the best performance and avoid using the fallback user agents, it is recommended to include the full user agent database in your build.

    pyinstaller --add-data "cloudscraper/user_agent/browsers.json;cloudscraper/user_agent/" your_app.py
  4. Handle Cloudflare v3 JavaScript VM Challenges

    master

    Cloudflare v3 challenges run in a sandboxed JavaScript environment and require specific handling. While cloudscraper supports v3 by default, it is recommended to use the js2py interpreter and increase the delay to allow for complex challenge execution.

    To optimize for v3, use the following configuration:

    • interpreter='js2py': The most compatible interpreter for v3.
    • delay: Increase this value (e.g., 5) to allow more time for the challenge to solve.
    • enable_stealth=True: Provides additional protection against v3 detection.
    import cloudscraper
    
    # Optimized configuration for v3 challenges
    scraper = cloudscraper.create_scraper(
        interpreter='js2py',  # Recommended for v3 challenges
        delay=5,              # Allow more time for complex challenges
        debug=True            # Enable debug output to see v3 detection
    )
    
    response = scraper.get("https://example.com")
    print(response.text)
  5. Use cloudscraper to bypass Cloudflare

    master

    The simplest way to use cloudscraper is by calling create_scraper(). This returns a CloudScraper instance which inherits from requests.Session.

    You can use it exactly like the requests library (e.g., .get(), .post()). Any requests made to websites protected by Cloudflare anti-bot will be handled automatically. For the first visit to a Cloudflare-protected site, the script will sleep for approximately 5 seconds to allow the challenge to resolve.

    import cloudscraper
    
    scraper = cloudscraper.create_scraper()  # returns a CloudScraper instance
    # Or: scraper = cloudscraper.CloudScraper()  # CloudScraper inherits from requests.Session
    print(scraper.get("http://somesite.com").text)  # => "<!DOCTYPE html><html><head>..."
  6. Migrate from cloudscraper v2.x to v3.0.0

    master

    When migrating to v3.0.0, note the following changes:

    1. Python Version: You must use Python 3.8 or higher. Python 3.6+ is no longer supported.
    2. Dependencies: All dependencies (including requests, pyOpenSSL, and pyparsing) have been upgraded to newer major versions. New dependencies like brotli and certifi are now required.
    3. API Usage: While the basic cloudscraper.create_scraper() call still works, it is recommended to pass the new configuration parameters (session_refresh_interval, auto_refresh_on_403, max_403_retries) to take advantage of the improved reliability features.
  7. Integrate cloudscraper tokens with curl

    master

    You can use cloudscraper to bypass Cloudflare challenges and then pass the resulting cookies and User-Agent to a curl command via subprocess.

    import subprocess
    import cloudscraper
    
    url = "http://somesite.com"
    cookie_arg, user_agent = cloudscraper.get_cookie_string(url)
    
    # Using curl to make the request
    result = subprocess.check_output(
        [
            'curl',
            '--cookie',
            cookie_arg,
            '-A',
            user_agent,
            url
        ]
    )
  8. Configure Stealth Mode and Browser Emulation

    master

    For maximum compatibility with challenging websites, you can enable enable_stealth and provide stealth_options to mimic human behavior.

    Available stealth_options keys:

    • min_delay: Minimum delay between actions.
    • max_delay: Maximum delay between actions.
    • human_like_delays: Boolean to enable human-like timing.
    • randomize_headers: Boolean to randomize request headers.
    • browser_quirks: Boolean to enable browser-specific quirks.
    import cloudscraper
    
    # Advanced configuration for challenging websites
    scraper = cloudscraper.create_scraper(
        # Challenge handling
        interpreter='js2py',        # Best compatibility for v3 challenges
        delay=5,                    # Extra time for complex challenges
    
        # Stealth mode
        enable_stealth=True,
        stealth_options={
            'min_delay': 2.0,
            'max_delay': 6.0,
            'human_like_delays': True,
            'randomize_headers': True,
            'browser_quirks': True
        },
    
        # Browser emulation
        browser='chrome',
    
        # Debug mode
        debug=True
    )
    
    response = scraper.get("https://example.com")
  9. Configure cloudscraper for optimal 403 error prevention

    master

    To prevent 403 errors caused by TLS fingerprinting, request throttling, or concurrent request conflicts, use the following configuration when calling cloudscraper.create_scraper().

    Critical Settings for Stability:

    • min_request_interval: Set to 2.0 or higher to prevent TLS blocking.
    • max_concurrent_requests: Set to 1 to prevent concurrent TLS conflicts.
    • rotate_tls_ciphers: Set to True to avoid detection via cipher suite patterns.
    • auto_refresh_on_403: Set to True to enable automatic recovery from 403 errors.
    import cloudscraper
    
    # OPTIMAL CONFIGURATION for preventing your specific 403 issues
    scraper = cloudscraper.create_scraper(
        debug=True,  # Enable for monitoring (disable in production)
        
        # 🔑 KEY SETTINGS to prevent 403 errors
        min_request_interval=2.0,      # CRITICAL: Prevents TLS blocking
        max_concurrent_requests=1,     # CRITICAL: Prevents concurrent conflicts
        rotate_tls_ciphers=True,       # CRITICAL: Avoids cipher detection
        
        # 🛡️ Enhanced protection
        auto_refresh_on_403=True,      # Auto-recover from 403 errors
        max_403_retries=3,             # Max retry attempts
        session_refresh_interval=1800, # Refresh session every 30 minutes
        
        # 🥷 Optimized stealth mode
        enable_stealth=True,
        stealth_options={
            'min_delay': 1.0,          # Reasonable delays
            'max_delay': 3.0,
            'human_like_delays': True,
            'randomize_headers': True,
            'browser_quirks': True
        }
    )
    
    response = scraper.get('https://your-target-site.com')
  10. Troubleshoot Cloudflare bypassing issues

    master

    If you are unable to bypass Cloudflare protections, try the following steps:

    1. Change browser emulation: Some sites respond better to chrome vs firefox in the browser config.
    2. Enable stealth mode: Use enable_stealth=True to simulate human-like behavior.
    3. Use proxy rotation: Use rotating_proxies to avoid IP blocks or rate limits.
    4. Switch JS interpreters: Try different interpreters such as js2py, nodejs, or v8 via the interpreter argument.
  11. Use Proxy Rotation

    master

    You can provide a list of proxies to rotating_proxies to rotate the IP address for each request. Use proxy_options to define the rotation strategy and ban time.

    proxy_options keys:

    • rotation_strategy: The method of rotation (e.g., 'smart').
    • ban_time: Time in seconds to wait before reusing a proxy.
    import cloudscraper
    
    proxies = [
        'http://user:pass@proxy1.example.com:8080',
        'http://user:pass@proxy2.example.com:8080',
        'http://user:pass@proxy3.example.com:8080'
    ]
    
    scraper = cloudscraper.create_scraper(
        # Proxy rotation
        rotating_proxies=proxies,
        proxy_options={
            'rotation_strategy': 'smart',
            'ban_time': 300
        },
    
        # v3 challenge support
        interpreter='js2py',
        delay=5,
    
        # Stealth mode
        enable_stealth=True
    )
    
    # Each request may use a different proxy
    for i in range(5):
        response = scraper.get("https://example.com")
        print(f"Request {i+1}: {response.status_code}")