My Python code is downloading images in poor quality and small size. How can I fix this?

I’m working on a Python program that reads a list of names from a text file, searches for each name on Google Images, and downloads the 11th image result (since the first 10 aren’t relevant). Although my code functions correctly, the images it downloads are much smaller than the originals.

How can I resolve this issue?

(This is my first time posting, so please let me know if I’ve made any mistakes or if there’s anything I should improve.)

Here’s the code I used (some parts are in Italian, but I hope that won’t be an issue):

import os
import time
import base64
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 selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from webdriver_manager.chrome import ChromeDriverManager

NUMERO_PASSI = 10  # Numero di nomi da aprire per ogni batch
DOWNLOAD_PATH = "C:\Users\Gabri\Pictures\Downloads"

def apri_schede_e_scarica_immagine(nome, driver):
    try:
        # URL con tentativo di disattivare SafeSearch
        url = f"https://www.google.com/search?tbm=isch&safe=off&q={nome}"
        driver.get(url)
        
        # Attendi che le immagini siano caricate
        WebDriverWait(driver, 10).until(
            EC.presence_of_element_located((By.CSS_SELECTOR, 'img'))
        )
        
        # Trova tutte le immagini
        img_elements = driver.find_elements(By.CSS_SELECTOR, 'img')
        if len(img_elements) > 10:  # Assicurati che ci siano almeno 11 immagini
            img_url = img_elements[10].get_attribute('src')  # Usa l'indice 10 per prendere l'11a immagine
            if img_url:
                salva_immagine(nome, img_url)
            else:
                print(f"Nessun URL trovato per l'immagine di {nome}.")
        else:
            print(f"Non ci sono abbastanza immagini per {nome}.")
    except Exception as e:
        print(f"Errore durante la ricerca e il download per {nome}: {e}")

def salva_immagine(nome, img_url):
    try:
        if img_url.startswith('data:image'):
            # Gestione dei URI di dati
            header, encoded = img_url.split(",", 1)
            data = base64.b64decode(encoded)
            file_extension = header.split(";")[0].split("/")[1]
            file_path = os.path.join(DOWNLOAD_PATH, f"{nome}.{file_extension}")
            with open(file_path, 'wb') as file:
                file.write(data)
        else:
            # Gestione degli URL HTTP
            response = requests.get(img_url)
            if response.status_code == 200:
                file_extension = img_url.split('.')[-1]
                file_path = os.path.join(DOWNLOAD_PATH, f"{nome}.{file_extension}")
                with open(file_path, 'wb') as file:
                    file.write(response.content)
            else:
                print(f"Impossibile scaricare l'immagine per {nome}. Status code: {response.status_code}")
        print(f"Immagine salvata per {nome}!")
    except Exception as e:
        print(f"Errore durante il salvataggio dell'immagine per {nome}: {e}")

def leggi_nomi_da_file(file_path):
    with open(file_path, 'r') as file:
        nomi = file.readlines()
    nomi = [nome.strip() for nome in nomi if nome.strip()]
    return nomi

def main():
    file_path = 'Nomi.txt'
    nomi = leggi_nomi_da_file(file_path)
    
    chrome_options = Options()
    chrome_options.add_argument("--headless")
    driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()), options=chrome_options)
    
    for nome in nomi:
        apri_schede_e_scarica_immagine(nome, driver)
        time.sleep(0.1)  # Ridotto il tempo di attesa a 0,1 secondi

    driver.quit()
    print("Tutte le schede sono state aperte e le immagini sono state scaricate. Programma terminato.")

if __name__ == "__main__":
    main()

I tried asking ChatGPT for help, but it couldn’t resolve my issue. I also searched on Google but didn’t find anything particularly useful.

New contributor

Gabriele Ranzari is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật