Spaces:
Paused
Paused
Upload 3 files
Browse filesFiles changed (3)
- DockerfileAdded+31
- main.pyAdded+184
- requirements.txtAdded+8
12345678910111213141516171819202122232425262728293031# We use a slim Debian-based Linux imageFROM python:3.12-slim
# Install system libraries required to run real Chromium + XvfbRUN apt-get update && apt-get install -y \ wget gnupg unzip curl \ xvfb libnss3 libgconf-2-4 \ libfontconfig1 libxrender1 \ libxext6 libx11-6 x11-utils \ chromium chromium-driver \ && rm -rf /var/lib/apt/lists/*
# Set up the working directory inside the containerWORKDIR /app
# Install our dependenciesCOPY requirements.txt .RUN pip install --no-cache-dir -r requirements.txt
# Copy our powerful API codeCOPY main.py .
# Expose port 8000 for the host platformEXPOSE 8000
# THE BYPASS TRICK: # We run Uvicorn wrapped in `xvfb-run` (X virtual framebuffer).# This "fakes" a physical computer monitor so that even inside a headless Linux server, # Chromium thinks it's running visibly on a real desk. # Cloudflare looks for screen dimensions; this fools them flawlessly!CMD ["xvfb-run", "-a", "uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184import timeimport asyncioimport osfrom fastapi import FastAPI, HTTPException, Securityfrom fastapi.security import APIKeyHeaderfrom pydantic import BaseModelfrom curl_cffi import requests as curl_requestsimport cloudscraperfrom scrapling.fetchers import StealthyFetcherfrom seleniumbase import Driverfrom typing import Optionalfrom concurrent.futures import ThreadPoolExecutor
app = FastAPI(title="4-Stage Cloudflare Bypass API")
API_KEY_SECRET = os.getenv("API_KEY", "my_secret_key_123")api_key_header = APIKeyHeader(name="X-API-Key", auto_error=True)
def verify_api_key(api_key: str = Security(api_key_header)): if api_key != API_KEY_SECRET: raise HTTPException(status_code=403, detail="Invalid API Key") return api_key
# Thread pool so browser stages don't block the server event loopexecutor = ThreadPoolExecutor(max_workers=4)
class ScrapeRequest(BaseModel): url: str proxy: Optional[str] = None cookies: Optional[dict] = None user_agent: Optional[str] = None
def is_blocked(text: str, status_code: int) -> bool: return ( status_code in [403, 503] or "Just a moment..." in text or "cf-turnstile" in text or "Enable JavaScript and cookies to continue" in text or "Checking your browser" in text or "cf_chl_opt" in text or "Attention Required" in text )
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# STAGE 1 β curl_cffi | ~0.3-0.7s | ~5MB | ~60% win# TLS/JA3/HTTP2 Chrome fingerprint spoof. Pure network layer.# Wins on: most WAF-only CF sites, DDoS protection only sites# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββdef _stage1(url, proxies, cookies, ua): try: session = curl_requests.Session(impersonate="chrome120", proxies=proxies) if ua: session.headers.update({"User-Agent": ua}) for k, v in (cookies or {}).items(): session.cookies.set(k, v) r = session.get(url, timeout=12) if not is_blocked(r.text, r.status_code): return {"html": r.text, "cookies": dict(r.cookies), "user_agent": ua or "chrome120"} except Exception: pass return None
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# STAGE 2 β Scrapling | ~3-8s | ~80MB | ~75% win# HTTP/3 + browser fingerprinting + native Turnstile solver# Wins on: Turnstile widgets, IUAM with JS checks# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββdef _stage2(url, proxy): try: proxies = {"http": proxy, "https": proxy} if proxy else None page = StealthyFetcher.fetch(url, headless=True, network_idle=False, proxy=proxies) if page and not is_blocked(page.text, page.status): return { "html": page.content, "cookies": {c["name"]: c["value"] for c in (page.cookies or [])}, "user_agent": "" } except Exception: pass return None
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# STAGE 3 β cloudscraper | ~1-3s | ~30MB | ~80% win# Built-in JS engine solves IUAM v1/v2/v3 classic challenges# Wins on: older CF protection, IUAM pages without Turnstile# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββdef _stage3(url, proxies): try: scraper = cloudscraper.create_scraper( browser={"browser": "chrome", "platform": "windows", "mobile": False} ) if proxies: scraper.proxies = proxies r = scraper.get(url, timeout=15) if not is_blocked(r.text, r.status_code): return { "html": r.text, "cookies": dict(r.cookies), "user_agent": scraper.headers.get("User-Agent", "") } except Exception: pass return None
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# STAGE 4 β SeleniumBase CDP | ~10-20s | ~600MB | ~99% win# Full browser via Chrome DevTools Protocol. Zero mouse movements.# Wins on: everything β hardcore Turnstile, visual puzzles, WAFs# ββββββββββββββββββββββββββββββοΏ½οΏ½ββββββββββββββββββββββββββdef _stage4(url, proxy): driver = Driver(uc=True, headless=False, proxy=proxy) try: driver.uc_activate_cdp_mode(url) driver.sleep(3) try: driver.cdp.gui_click_element("input[type='checkbox']") driver.sleep(2) except Exception: pass token = None for _ in range(20): try: val = driver.execute_script(""" var t = document.querySelector('input[name="cf-turnstile-response"]'); if (t && t.value) return t.value; var g = document.querySelector('textarea[name="g-recaptcha-response"]'); if (g && g.value) return g.value; return null; """) if val: token = val break except Exception: pass driver.sleep(1) return { "token": token, "user_agent": driver.execute_script("return navigator.userAgent;"), "cookies": {c["name"]: c["value"] for c in driver.get_cookies()}, "html": driver.get_page_source() } finally: driver.quit()
@app.post("/scrape")async def scrape(request: ScrapeRequest, api_key: str = Security(verify_api_key)): start = time.time() proxies = {"http": request.proxy, "https": request.proxy} if request.proxy else None loop = asyncio.get_event_loop()
# Run all blocking IO in thread pool so server never freezes
# Stage 1 β instant result = await loop.run_in_executor(executor, _stage1, request.url, proxies, request.cookies, request.user_agent) if result: return {"status": "success", "stage": 1, "method": "curl_cffi", "time_seconds": round(time.time() - start, 2), **result, "token": None}
# Stage 2 β Scrapling result = await loop.run_in_executor(executor, _stage2, request.url, request.proxy) if result: return {"status": "success", "stage": 2, "method": "Scrapling StealthyFetcher", "time_seconds": round(time.time() - start, 2), **result, "token": None}
# Stage 3 β cloudscraper result = await loop.run_in_executor(executor, _stage3, request.url, proxies) if result: return {"status": "success", "stage": 3, "method": "cloudscraper", "time_seconds": round(time.time() - start, 2), **result, "token": None}
# Stage 4 β CDP full browser (nuclear option) try: result = await loop.run_in_executor(executor, _stage4, request.url, request.proxy) return { "status": "success", "stage": 4, "method": "SeleniumBase CDP", "time_seconds": round(time.time() - start, 2), "html": result["html"][:5000], "cookies": result["cookies"], "user_agent": result["user_agent"], "token": result["token"] } except Exception as e: raise HTTPException(status_code=500, detail=f"All 4 stages failed: {str(e)}")12345678fastapiuvicornseleniumbasepydanticrequestscurl_cfficloudscraperscrapling[fetchers]DockerfileAdded+31
main.pyAdded+184
requirements.txtAdded+8