|
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 |
import os import time import requests 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 webdriver_manager.chrome import ChromeDriverManager # Install Google Chrome !wget -q -O - https://dl-ssl.google.com/linux/linux_signing_key.pub | apt-key add - !echo "deb [arch=amd64] http://dl.google.com/linux/chrome/deb/ stable main" >> /etc/apt/sources.list.d/google-chrome.list !apt-get update !apt-get install -y google-chrome-stable def descargar_imagenes_google(url_busqueda, carpeta_destino): # Configurar opciones de Chrome chrome_options = Options() chrome_options.add_argument("--headless") # Run in headless mode (without opening a browser window) chrome_options.add_argument("--no-sandbox") # Required for Colab environment chrome_options.add_argument("--disable-dev-shm-usage") # Overcomes limited resource problems chrome_options.binary_location = '/usr/bin/google-chrome' # Specify Chrome binary location for google-chrome-stable # Inicializar el driver driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()), options=chrome_options) if not os.path.exists(carpeta_destino): os.makedirs(carpeta_destino) try: driver.get(url_busqueda) time.sleep(3) # Esperar a que cargue # Hacer scroll hacia abajo para cargar más imágenes print("Cargando imágenes...") for _ in range(5): # Ajusta el rango para más o menos fotos driver.execute_script("window.scrollBy(0, 1000);") time.sleep(2) # Encontrar todas las etiquetas de imagen # Google suele usar etiquetas img dentro de resultados de búsqueda thumbnails = driver.find_elements(By.CSS_SELECTOR, "img") count = 0 for i, img in enumerate(thumbnails): try: # Obtener la URL de la imagen (src) src = img.get_attribute('src') if src and src.startswith('http'): response = requests.get(src, timeout=10) if response.status_code == 200: with open(os.path.join(carpeta_destino, f"imagen_{count}.jpg"), 'wb') as f: f.write(response.content) count += 1 print(f"Descargada imagen {count}") # Google también usa imágenes en formato base64 (data:image/...) elif src and src.startswith('data:image'): # Opcional: Manejar imágenes base64 si es necesario pass except Exception as e: print(f"No se pudo descargar la imagen {i}: {e}") finally: driver.quit() print(f"Proceso finalizado. {count} imágenes guardadas en '{carpeta_destino}'.") # URL proporcionada url = "https://www.google.com/search?sca_esv=" descargar_imagenes_google(url, "fotos_jesusninoc") |

