Bot commited on
Commit Β·
de22b07
1
Parent(s): 2387d73
Add POST request support with method, headers, and data fields
Browse files12345678910111268 unmodified lines81828384858651 unmodified lines1381391401411421431441451461471481493 unmodified lines15315415515615715815916023 unmodified lines1841851861871881891905 unmodified lines196197198199200201202203271 unmodified lines475476477478479480481482394 unmodified lines87787887988088188288323 unmodified lines90790890991091191291313 unmodified lines92792892993093193293330 unmodified lines96496596696796896997097197297397497597697797897998045 unmodified lines1026102710281029103010311032103310341035103610371038103910401041104236 unmodified lines1079108010811082108310841085108610871088108910901091109210931094109513 unmodified lines11091110111111121113111411151116111711181119112011211122112311241125import timeimport asyncioimport osfrom fastapi import FastAPI, HTTPException, Security, Requestfrom fastapi.security import APIKeyHeaderfrom pydantic import BaseModelfrom curl_cffi import requests as curl_requestsimport cloudscraperfrom typing import Optionalfrom concurrent.futures import ThreadPoolExecutorfrom urllib.parse import urlparse68 unmodified linesclass ScrapeRequest(BaseModel):url: strproxy: Optional[str] = Nonecookies: Optional[dict] = Noneuser_agent: Optional[str] = None51 unmodified lines# Accept if it has title + length, UNLESS it's obviously a CF challengereturn has_title and has_length and not is_obvious_cf_challenge# ββββββββββββββοΏ½οΏ½οΏ½ββββββββββββββββββββββββββββββββββββββββββ# 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:print(f"[Stage 1] Starting for {url}")session = curl_requests.Session(impersonate="chrome120", proxies=proxies)3 unmodified linesfor k, v in (cookies or {}).items():session.cookies.set(k, v)print(f"[Stage 1] Sending GET request (timeout: 12s)...")r = session.get(url, timeout=12)print(f"[Stage 1] Got response: status={r.status_code}, content_length={len(r.text)}")# Check if blocked OR if content is invalid23 unmodified lines# 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:print(f"[Stage 3] Starting for {url}")scraper = cloudscraper.create_scraper(5 unmodified linesscraper.proxies = proxiesprint(f"[Stage 3] Using proxies: {proxies}")print(f"[Stage 3] Sending GET request (timeout: 15s)...")r = scraper.get(url, timeout=15)print(f"[Stage 3] Got response: status={r.status_code}, content_length={len(r.text)}")# Check if blocked OR if content is invalid271 unmodified linespage.wait_for_load_state("load")print("[Stage 4] Page load state confirmed")html = page.content()print(f"[Stage 4] Got HTML: {len(html)} bytes")cookies_list = context.cookies()cookies = {c["name"]: c["value"] for c in cookies_list}print(f"[Stage 4] Got {len(cookies)} cookies")394 unmodified lines"status": "success","stage": 4,"url": url,"html": result["html"][:50000],"cookies": result["cookies"],"user_agent": result["user_agent"],"time_seconds": round(time.time() - start, 2)23 unmodified lines# Stage 1 β instantprint(f"[Scrape] Trying Stage 1 (curl_cffi)...")result = await loop.run_in_executor(executor, _stage1, request_data.url, proxies, request_data.cookies, user_agent)if result:# Cache the cookies with IP + UAcache_cookies(request_data.url, result["cookies"], user_agent, client_ip)13 unmodified lines# Stage 3 β cloudscraper (Stage 2 removed - Scrapling not available on HF)print(f"[Scrape] Trying Stage 3 (cloudscraper)...")result = await loop.run_in_executor(executor, _stage3, request_data.url, proxies)if result:# Cache the cookies with IP + UAcache_cookies(request_data.url, result["cookies"], user_agent, client_ip)30 unmodified linescache_cookies(request_data.url, result["cookies"], user_agent, client_ip)print(f"[Scrape] Stage 3B (hCaptcha Solver) succeeded!")return {"status": "success","stage": "3B","method": "Selenium + Tampermonkey (hCaptcha)","time_seconds": round(time.time() - start, 2),"html": result["html"][:10000] if result["html"] else "","cookies": result["cookies"],"user_agent": result["user_agent"],"token": None,"cf_clearance": result["cookies"].get("cf_clearance"),"cached": False,"note": "hCaptcha solved with Selenium + Tampermonkey"}45 unmodified linescache_cookies(request_data.url, dict(page_response.cookies), user_agent, client_ip)print(f"[Scrape] Stage 2B (Turnstile Solver) succeeded!")return {"status": "success","stage": "2B","method": "Theyka/Turnstile-Solver","time_seconds": round(time.time() - start, 2),"html": page_html[:10000] if page_html else "","cookies": dict(page_response.cookies),"user_agent": user_agent or "Mozilla/5.0","token": token,"cf_clearance": token,"cached": False,"note": "Turnstile token extracted and page fetched"}except Exception as e:36 unmodified lines# Extract cf_clearance cookie for future usecf_clearance = result["cookies"].get("cf_clearance")return {"status": "success","stage": "4B","method": "nodriver (Undetected)","time_seconds": round(time.time() - start, 2),"html": result["html"][:10000],"cookies": result["cookies"],"user_agent": result["user_agent"],"token": result["token"],"cf_clearance": cf_clearance,"cached": False,"note": "Use cf_clearance cookie in future Stage 1 requests for this domain"}print(f"[Scrape] Stage 4B returned None, trying Stage 4 (Playwright)...")13 unmodified lines# Extract cf_clearance cookie for future usecf_clearance = result["cookies"].get("cf_clearance")return {"status": "success","stage": 4,"method": "Playwright (Stealth)","time_seconds": round(time.time() - start, 2),"html": result["html"][:10000],"cookies": result["cookies"],"user_agent": result["user_agent"],"token": result["token"],"cf_clearance": cf_clearance,"cached": False,"note": "Use cf_clearance cookie in future Stage 1 requests for this domain"}print(f"[Scrape] Stage 4 returned None")12345678910111213141568 unmodified lines84858687888990919251 unmodified lines1441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522533 unmodified lines25725825926026126226326426526623 unmodified lines2902912922932942952965 unmodified lines302303304305306307308309310311271 unmodified lines583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615394 unmodified lines101010111012101310141015101623 unmodified lines104010411042104310441045104613 unmodified lines106010611062106310641065106630 unmodified lines109710981099110011011102110311041105110611071108110911101111111211131114111511161117111845 unmodified lines11641165116611671168116911701171117211731174117511761177117811791180118111821183118436 unmodified lines122112221223122412251226122712281229123012311232123312341235123612371238123912401241124213 unmodified lines1256125712581259126012611262126312641265126612671268126912701271127212731274127512761277import timeimport asyncioimport osimport jsonimport reimport uuidfrom fastapi import FastAPI, HTTPException, Security, Requestfrom fastapi.security import APIKeyHeaderfrom pydantic import BaseModelfrom curl_cffi import requests as curl_requestsimport cloudscraperfrom typing import Optional, Dict, Tuplefrom concurrent.futures import ThreadPoolExecutorfrom urllib.parse import urlparse68 unmodified linesclass ScrapeRequest(BaseModel):url: strmethod: Optional[str] = "GET"headers: Optional[dict] = Nonedata: Optional[str] = Noneproxy: Optional[str] = Nonecookies: Optional[dict] = Noneuser_agent: Optional[str] = None51 unmodified lines# Accept if it has title + length, UNLESS it's obviously a CF challengereturn has_title and has_length and not is_obvious_cf_challengedef _extract_credentials(html: str) -> Dict:"""Extract credentials from HTML (uniqueid, verify token, API keys, etc.)"""credentials = {}try:# Extract uniqueid (32-char hex)uniqueid_patterns = [r'"uniqueid"\s*:\s*"([a-f0-9]{32})"',r'uniqueid["\']?\s*[:=]\s*["\']([a-f0-9]{32})["\']',r'localStorage\.setItem\(["\']uniqueid["\'],\s*["\']([a-f0-9]{32})["\']',r'window\.uniqueid\s*=\s*["\']([a-f0-9]{32})["\']',r'const\s+uniqueid\s*=\s*["\']([a-f0-9]{32})["\']',r'uniqueid["\']?\s*:\s*["\']([a-f0-9]{32})["\']',]for pattern in uniqueid_patterns:match = re.search(pattern, html, re.IGNORECASE)if match:credentials["uniqueid"] = match.group(1)print(f"[Credentials] Found uniqueid: {match.group(1)[:16]}...")break# Extract verify token (JWT starting with P1_)verify_patterns = [r'"verify"\s*:\s*"(P1_[^"]+)"',r'verify["\']?\s*[:=]\s*["\']([^"\']+)["\']',r'localStorage\.setItem\(["\']verify["\'],\s*["\']([^"\']+)["\']',r'window\.verify\s*=\s*["\']([^"\']+)["\']',r'const\s+verify\s*=\s*["\']([^"\']+)["\']',r'"token"\s*:\s*"(P1_[^"]+)"',r'authorization["\']?\s*:\s*["\']Bearer\s+([^"\']+)["\']',r'verify["\']?\s*:\s*["\']([^"\']+)["\']',]for pattern in verify_patterns:match = re.search(pattern, html, re.IGNORECASE)if match:token = match.group(1)credentials["verify"] = tokenprint(f"[Credentials] Found verify token: {token[:30]}...")break# Extract API keysapi_key_patterns = [r'"api[_-]?key"\s*:\s*"([^"]+)"',r'apiKey["\']?\s*[:=]\s*["\']([^"\']+)["\']',r'API_KEY\s*=\s*["\']([^"\']+)["\']',r'x-api-key["\']?\s*:\s*["\']([^"\']+)["\']',]for pattern in api_key_patterns:match = re.search(pattern, html, re.IGNORECASE)if match:credentials["api_key"] = match.group(1)print(f"[Credentials] Found API key: {match.group(1)[:20]}...")break# Extract auth tokensauth_patterns = [r'"auth[_-]?token"\s*:\s*"([^"]+)"',r'authToken["\']?\s*[:=]\s*["\']([^"\']+)["\']',r'AUTH_TOKEN\s*=\s*["\']([^"\']+)["\']',r'authorization["\']?\s*:\s*["\']([^"\']+)["\']',]for pattern in auth_patterns:match = re.search(pattern, html, re.IGNORECASE)if match:credentials["auth_token"] = match.group(1)print(f"[Credentials] Found auth token: {match.group(1)[:20]}...")break# Extract session IDsession_patterns = [r'"session[_-]?id"\s*:\s*"([^"]+)"',r'sessionId["\']?\s*[:=]\s*["\']([^"\']+)["\']',r'SESSION_ID\s*=\s*["\']([^"\']+)["\']',r'JSESSIONID["\']?\s*[:=]\s*["\']([^"\']+)["\']',]for pattern in session_patterns:match = re.search(pattern, html, re.IGNORECASE)if match:credentials["session_id"] = match.group(1)print(f"[Credentials] Found session ID: {match.group(1)[:20]}...")breakif credentials:print(f"[Credentials] Extracted {len(credentials)} credentials from HTML")else:print(f"[Credentials] No credentials found in HTML (they may be in localStorage)")return credentialsexcept Exception as e:print(f"[Credentials] Error extracting: {type(e).__name__}: {str(e)[:100]}")return {}# ββββββββββββββοΏ½οΏ½οΏ½ββββββββββββββββββββββββββββββββββββββββββ# 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, method="GET", headers=None, data=None):try:print(f"[Stage 1] Starting for {url}")session = curl_requests.Session(impersonate="chrome120", proxies=proxies)3 unmodified linesfor k, v in (cookies or {}).items():session.cookies.set(k, v)if headers:session.headers.update(headers)print(f"[Stage 1] Sending {method.upper()} request (timeout: 12s)...")r = session.request(method.upper(), url, data=data, timeout=12)print(f"[Stage 1] Got response: status={r.status_code}, content_length={len(r.text)}")# Check if blocked OR if content is invalid23 unmodified lines# Built-in JS engine solves IUAM v1/v2/v3 classic challenges# Wins on: older CF protection, IUAM pages without Turnstile# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββdef _stage3(url, proxies, method="GET", headers=None, data=None):try:print(f"[Stage 3] Starting for {url}")scraper = cloudscraper.create_scraper(5 unmodified linesscraper.proxies = proxiesprint(f"[Stage 3] Using proxies: {proxies}")if headers:scraper.headers.update(headers)print(f"[Stage 3] Sending {method.upper()} request (timeout: 15s)...")r = scraper.request(method.upper(), url, data=data, timeout=15)print(f"[Stage 3] Got response: status={r.status_code}, content_length={len(r.text)}")# Check if blocked OR if content is invalid271 unmodified linespage.wait_for_load_state("load")print("[Stage 4] Page load state confirmed")# Wait for JavaScript to execute and populate localStorageprint("[Stage 4] Waiting for JavaScript to initialize (3s)...")page.wait_for_timeout(3000)print("[Stage 4] JavaScript initialization complete")html = page.content()print(f"[Stage 4] Got HTML: {len(html)} bytes")# Extract credentials from localStorageprint("[Stage 4] Extracting credentials from localStorage...")try:local_storage = page.evaluate("""() => {const storage = {};for (let i = 0; i < localStorage.length; i++) {const key = localStorage.key(i);storage[key] = localStorage.getItem(key);}return storage;}""")print(f"[Stage 4] Got localStorage with {len(local_storage)} items")# Add localStorage to HTML for extractionhtml += f"\n<!-- localStorage: {json.dumps(local_storage)} -->"except Exception as e:print(f"[Stage 4] Could not extract localStorage: {e}")cookies_list = context.cookies()cookies = {c["name"]: c["value"] for c in cookies_list}print(f"[Stage 4] Got {len(cookies)} cookies")394 unmodified lines"status": "success","stage": 4,"url": url,"html": result["html"],"cookies": result["cookies"],"user_agent": result["user_agent"],"time_seconds": round(time.time() - start, 2)23 unmodified lines# Stage 1 β instantprint(f"[Scrape] Trying Stage 1 (curl_cffi)...")result = await loop.run_in_executor(executor, _stage1, request_data.url, proxies, request_data.cookies, user_agent, request_data.method, request_data.headers, request_data.data)if result:# Cache the cookies with IP + UAcache_cookies(request_data.url, result["cookies"], user_agent, client_ip)13 unmodified lines# Stage 3 β cloudscraper (Stage 2 removed - Scrapling not available on HF)print(f"[Scrape] Trying Stage 3 (cloudscraper)...")result = await loop.run_in_executor(executor, _stage3, request_data.url, proxies, request_data.method, request_data.headers, request_data.data)if result:# Cache the cookies with IP + UAcache_cookies(request_data.url, result["cookies"], user_agent, client_ip)30 unmodified linescache_cookies(request_data.url, result["cookies"], user_agent, client_ip)print(f"[Scrape] Stage 3B (hCaptcha Solver) succeeded!")# Extract credentials from HTMLhtml_full = result["html"]extracted_creds = _extract_credentials(html_full)return {"status": "success","stage": "3B","method": "Selenium + Tampermonkey (hCaptcha)","time_seconds": round(time.time() - start, 2),"html": html_full if html_full else "","cookies": result["cookies"],"user_agent": result["user_agent"],"token": None,"cf_clearance": result["cookies"].get("cf_clearance"),"cached": False,"credentials": extracted_creds,"note": "hCaptcha solved with Selenium + Tampermonkey"}45 unmodified linescache_cookies(request_data.url, dict(page_response.cookies), user_agent, client_ip)print(f"[Scrape] Stage 2B (Turnstile Solver) succeeded!")# Extract credentials from HTMLextracted_creds = _extract_credentials(page_html)return {"status": "success","stage": "2B","method": "Theyka/Turnstile-Solver","time_seconds": round(time.time() - start, 2),"html": page_html if page_html else "","cookies": dict(page_response.cookies),"user_agent": user_agent or "Mozilla/5.0","token": token,"cf_clearance": token,"cached": False,"credentials": extracted_creds,"note": "Turnstile token extracted and page fetched"}except Exception as e:36 unmodified lines# Extract cf_clearance cookie for future usecf_clearance = result["cookies"].get("cf_clearance")# Extract credentials from HTMLhtml_full = result["html"]extracted_creds = _extract_credentials(html_full)return {"status": "success","stage": "4B","method": "nodriver (Undetected)","time_seconds": round(time.time() - start, 2),"html": html_full,"cookies": result["cookies"],"user_agent": result["user_agent"],"token": result["token"],"cf_clearance": cf_clearance,"cached": False,"credentials": extracted_creds,"note": "Use cf_clearance cookie in future Stage 1 requests for this domain"}print(f"[Scrape] Stage 4B returned None, trying Stage 4 (Playwright)...")13 unmodified lines# Extract cf_clearance cookie for future usecf_clearance = result["cookies"].get("cf_clearance")# Extract credentials from HTMLhtml_full = result["html"]extracted_creds = _extract_credentials(html_full)return {"status": "success","stage": 4,"method": "Playwright (Stealth)","time_seconds": round(time.time() - start, 2),"html": html_full,"cookies": result["cookies"],"user_agent": result["user_agent"],"token": result["token"],"cf_clearance": cf_clearance,"cached": False,"credentials": extracted_creds,"note": "Use cf_clearance cookie in future Stage 1 requests for this domain"}print(f"[Scrape] Stage 4 returned None")
main.py+166-14