Download src/backend/scraper/screenshot_module.py from MonPrinM/README: direct link, hf CLI and curl.
- Browser
- Download file 5.08 kB
-
https://huggingface.co/spaces/MonPrinM/README/resolve/main/src/backend/scraper/screenshot_module.py
- Command line
-
hf download hf://spaces/MonPrinM/README/src/backend/scraper/screenshot_module.py
-
curl -L -o screenshot_module.py https://huggingface.co/spaces/MonPrinM/README/resolve/main/src/backend/scraper/screenshot_module.py
5.08 kB
| import json | |
| import os | |
| import random | |
| from playwright.sync_api import sync_playwright, Error as PlaywrightError | |
| USER_AGENTS = [ | |
| "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36", | |
| "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36", | |
| ] | |
| def take_screenshots(input_file, output_dir, logger): | |
| """Capture website screenshots""" | |
| if not os.path.exists(output_dir): | |
| os.makedirs(output_dir) | |
| sites = [] | |
| try: | |
| with open(input_file, 'r', encoding='utf-8') as f: | |
| for line in f: | |
| if line.strip(): | |
| sites.append(json.loads(line)) | |
| except FileNotFoundError: | |
| logger.log("Data file not found", level="ERROR") | |
| return 0 | |
| screenshot_count = 0 | |
| with sync_playwright() as p: | |
| browser = p.chromium.launch( | |
| headless=True, | |
| args=[ | |
| "--disable-blink-features=AutomationControlled", | |
| "--no-sandbox", | |
| "--disable-setuid-sandbox" | |
| ] | |
| ) | |
| context = browser.new_context( | |
| viewport={'width': 1920, 'height': 1080}, | |
| user_agent=random.choice(USER_AGENTS), | |
| locale="en-GB", | |
| timezone_id="Europe/London" | |
| ) | |
| context.add_init_script(""" | |
| Object.defineProperty(navigator, 'webdriver', { | |
| get: () => undefined | |
| }); | |
| """) | |
| page = context.new_page() | |
| for index, site in enumerate(sites): | |
| url = site.get('website') | |
| name = site.get('name', 'Unknown') | |
| file_index = f"{index + 1:03d}" | |
| filename = f"{file_index}_screenshot.png" | |
| filepath = os.path.join(output_dir, filename) | |
| if not url: | |
| continue | |
| logger.log(f"[{file_index}] Accessing: {url}") | |
| try: | |
| # --- FIX START: Handle Redirects --- | |
| try: | |
| response = page.goto(url, timeout=60000, wait_until='domcontentloaded') | |
| except PlaywrightError as e: | |
| # If the navigation is interrupted by a redirect, we catch it and wait for the new page | |
| if "interrupted by another navigation" in str(e): | |
| logger.log("Redirect detected, waiting for new page load...") | |
| try: | |
| page.wait_for_load_state("domcontentloaded", timeout=30000) | |
| except: | |
| pass # If it times out, we try to screenshot anyway | |
| else: | |
| raise e # If it's a different error, re-raise it to the outer except block | |
| # --- FIX END --- | |
| page.wait_for_timeout(3000) | |
| # Check for Cloudflare | |
| cloudflare_indicators = [ | |
| "Verify you are human", | |
| "Checking your browser before accessing", | |
| "Just a moment..." | |
| ] | |
| page_content = page.content() | |
| if any(indicator in page_content for indicator in cloudflare_indicators): | |
| logger.log(f"Cloudflare detected, attempting bypass...") | |
| try: | |
| frame_element = page.frame_locator("iframe[src*='cloudflare']").first | |
| checkbox = frame_element.locator("input[type='checkbox'], span.mark").first | |
| if checkbox.is_visible(): | |
| box = checkbox.bounding_box() | |
| if box: | |
| page.mouse.move(box['x'] + 5, box['y'] + 5) | |
| page.wait_for_timeout(random.randint(200, 500)) | |
| page.mouse.down() | |
| page.wait_for_timeout(random.randint(50, 150)) | |
| page.mouse.up() | |
| logger.log("Clicked Cloudflare") | |
| page.wait_for_timeout(5000) | |
| except Exception as e: | |
| logger.log(f"Failed to click: {e}") | |
| # Close cookie banner | |
| try: | |
| page.locator("button:text-matches('Accept|Agree|Allow|Cookie|Принять', 'i')").first.click(timeout=2000) | |
| page.wait_for_timeout(1000) | |
| except: | |
| pass | |
| page.screenshot(path=filepath) | |
| screenshot_count += 1 | |
| logger.log(f"Screenshot saved: {filename}") | |
| except Exception as e: | |
| logger.log(f"Error: {e}", level="ERROR") | |
| browser.close() | |
| return screenshot_count |