File size: 6,544 Bytes
dfe70ff
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
import os
import time
import random
import requests
from urllib.parse import urljoin
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from webdriver_manager.chrome import ChromeDriverManager
from bs4 import BeautifulSoup

# Configuration
BASE_URL = "https://openi.nlm.nih.gov"
SEARCH_URL = "https://openi.nlm.nih.gov/gridquery?it=xg&m=1&n=100&q=pneumonia%20x%20ray"
DATA_DIR = "xray_images"
DELAY_RANGE = (1, 3)
HEADERS = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36",
    "Referer": BASE_URL
}


def setup_driver():
    """Configure Chrome with advanced anti-detection settings"""
    chrome_options = Options()
    chrome_options.add_argument("--headless=new")
    chrome_options.add_argument("--disable-blink-features=AutomationControlled")
    chrome_options.add_experimental_option("excludeSwitches", ["enable-automation"])
    chrome_options.add_experimental_option("useAutomationExtension", False)
    chrome_options.add_argument("--window-size=1920,1080")

    # Random user agent rotation
    user_agents = [
        "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36",
        "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36"
    ]
    chrome_options.add_argument(f"user-agent={random.choice(user_agents)}")

    service = Service(ChromeDriverManager().install())
    driver = webdriver.Chrome(service=service, options=chrome_options)

    # Mask WebDriver parameters
    driver.execute_cdp_cmd("Page.addScriptToEvaluateOnNewDocument", {
        "source": """
        Object.defineProperty(navigator, 'webdriver', {get: () => undefined});
        window.navigator.chrome = {runtime: {}};
        """
    })

    return driver


def load_full_page(driver):
    """Ensure all content is loaded with multiple scroll attempts"""
    print("Loading full page content...")
    for _ in range(3):
        driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
        time.sleep(random.uniform(2, 4))
        driver.execute_script("window.scrollTo(0, 0);")
        time.sleep(random.uniform(1, 2))


def extract_image_urls(driver):
    """Multi-strategy URL extraction with fallbacks"""
    print("Extracting image URLs...")
    soup = BeautifulSoup(driver.page_source, "html.parser")
    urls = []

    # Strategy 1: Direct image sources
    for img in soup.select('img[src*="/imgs/"]'):
        src = img.get('src', '')
        if src.endswith('.png'):
            urls.append(urljoin(BASE_URL, src))

    # Strategy 2: Angular data attributes (fallback)
    if not urls:
        for div in soup.select('div[data-ng-init*="img"]'):
            init_str = div.get('data-ng-init', '')
            if 'img:' in init_str:
                img_id = init_str.split("'")[3]
                urls.append(f"{BASE_URL}/imgs/collections/{img_id}.png")

    # Strategy 3: JavaScript-rendered content
    if not urls:
        script_tags = soup.find_all('script', type='text/javascript')
        for script in script_tags:
            if 'img:' in script.text:
                lines = script.text.split('\n')
                for line in lines:
                    if 'img:' in line:
                        img_id = line.split("'")[3]
                        urls.append(f"{BASE_URL}/imgs/collections/{img_id}.png")

    return list(set(urls))


def verify_download(url):
    """Validate image URLs before downloading"""
    try:
        head_response = requests.head(url, headers=HEADERS, timeout=10)
        if head_response.status_code == 200:
            return True
        print(f"Invalid URL: {url} (Status: {head_response.status_code})")
        return False
    except Exception as e:
        print(f"URL verification failed: {url} - {str(e)}")
        return False


def download_images(url_list):
    """Batch download with progress tracking"""
    os.makedirs(DATA_DIR, exist_ok=True)
    success_count = 0

    for idx, url in enumerate(url_list, 1):
        print(f"Processing {idx}/{len(url_list)}")

        if not verify_download(url):
            continue

        try:
            filename = url.split('/')[-1]
            filepath = os.path.join(DATA_DIR, filename)

            if os.path.exists(filepath):
                print(f"Skipping existing: {filename}")
                success_count += 1
                continue

            response = requests.get(url, headers=HEADERS, stream=True, timeout=30)
            response.raise_for_status()

            # Validate image content
            if response.headers['Content-Type'] not in ['image/png', 'image/jpeg']:
                raise ValueError("Invalid content type")

            with open(filepath, 'wb') as f:
                for chunk in response.iter_content(chunk_size=8192):
                    if chunk:  # Filter out keep-alive chunks
                        f.write(chunk)

            print(f"Downloaded: {filename}")
            success_count += 1

        except Exception as e:
            print(f"Download failed: {url} - {str(e)}")

        time.sleep(random.uniform(*DELAY_RANGE))

    return success_count


def main():
    driver = setup_driver()

    try:
        # Initial page load
        print("Navigating to search page...")
        driver.get(SEARCH_URL)

        # Wait for core content
        WebDriverWait(driver, 20).until(
            EC.presence_of_element_located((By.CSS_SELECTOR, "body"))
        )

        # Force full page load
        load_full_page(driver)

        # Extract URLs using multiple strategies
        image_urls = extract_image_urls(driver)

        if not image_urls:
            print("No URLs found - saving debug files...")
            with open("debug_page.html", "w", encoding="utf-8") as f:
                f.write(driver.page_source)
            driver.save_screenshot("debug_screenshot.png")
            return

        print(f"Found {len(image_urls)} potential image URLs")

        # Download images
        success = download_images(image_urls)
        print(f"\nDownload complete! Successfully saved {success}/{len(image_urls)} images")

    finally:
        driver.quit()


if __name__ == "__main__":
    main()