File size: 5,084 Bytes
1f8acec
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
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