File size: 3,355 Bytes
f262da8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
import requests
from curl_cffi import requests as curl_requests
import time
import os

# Read from environment, default to HF Spaces port
API_URL = os.getenv("API_URL", "http://127.0.0.1:7860/scrape")
API_KEY = os.getenv("API_KEY", "my_secret_key_123")

# A famously strict site to test the hybrid bypass
TARGET_SITE = "https://demo.turnstile.workers.dev/"

def call_heavy_browser_solver(url: str):
    """Triggers the invisible Chrome window to visually solve the Turnstile and steal cookies."""
    print(f"\n[!] Cloudflare JS Challenge activated.")
    print(f"[*] Waking up the Heavy Browser API to solve Turnstile for: {url}")
    
    headers = {"X-API-Key": API_KEY}
    # Send the payload expecting the API to route it appropriately (it handles headless config intrinsically via xvfb)
    response = requests.post(API_URL, headers=headers, json={
        "url": url,
    })
    
    response.raise_for_status()
    payload = response.json()
    
    print(f"[+] 🍪 Browsers extracted Cookie Payload: {len(payload.get('cookies', {}))} cookies")
    return payload

def run_hybrid_scraper(url: str):
    print("\n=== STARTING TIER 1 HYBRID NETWORK SCRAPER (3-STAGE) ===")
    print(f"[*] API URL: {API_URL}")
    
    # 1. Establish the "curl_cffi" network-spoofing session 
    # This flawlessly maths out the TLS and HTTP/2 packet structures of Chrome.
    session = curl_requests.Session(impersonate="chrome120")
    
    print(f"[*] Attempting Stage 1 Network Spoof bypass...")
    start_time = time.time()
    response = session.get(url)
    
    # We inspect the body. If it contains Cloudflare interstitial markers or 403 blocks...
    if "Just a moment..." in response.text or "cf-turnstile" in response.text or response.status_code in [403, 503]:
        print(f"[-] Stage 1 failed. The site forces JavaScript execution (HTTP {response.status_code}).")
        
        # 2. TRIGGER STAGE 2: THE SELENIUM BROWSER SOLVER
        solver_data = call_heavy_browser_solver(url)
        
        # 3. THE HANDOFF
        # We take the dynamic User-Agent and the clearance cookies from the heavy browser
        # and forcefully inject them into our lightweight 0-RAM network spoof session.
        print("\n[*] Handing off exact Browser Fingerprint to our lightweight spoof session...")
        session.headers.update({"User-Agent": solver_data["user_agent"]})
        
        for cookie_name, cookie_value in solver_data["cookies"].items():
            session.cookies.set(cookie_name, cookie_value)
            
        print("[*] Re-attempting instant HTML pull holding the golden CF Cookies...")
        fast_start = time.time()
        
        # 4. FINAL SCRAPE
        success_response = session.get(url)
        print(f"[+] Success! Downloaded website HTML flawlessly in {time.time() - fast_start:.3f} seconds!")
        print(f"[★] From now on, you can scrape ANY page on this site with this session instantly without triggering the browser API again!")
        
        return success_response.text
        
    else:
        print(f"[+] Incredible! Passed straight through on Stage A TLS impersonation! (Time: {time.time() - start_time:.3f}s)")
        return response.text

if __name__ == "__main__":
    html_output = run_hybrid_scraper(TARGET_SITE)
    print("\n--- Scraped Site Data Snippet ---")
    print(html_output[:500])