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()