-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathimage_downloader.py
More file actions
87 lines (70 loc) · 3.24 KB
/
Copy pathimage_downloader.py
File metadata and controls
87 lines (70 loc) · 3.24 KB
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
# Download immagini da una pagina web, inclusi contenuti Base64.
import os
import requests
import base64
from bs4 import BeautifulSoup
from urllib.parse import urljoin, urlparse, unquote
from PIL import Image
import io
def download_images(url):
# Creare la cartella export se non esiste
folder = "export"
if not os.path.exists(folder):
os.makedirs(folder)
# Scaricare il contenuto della pagina
try:
response = requests.get(url, headers={"User-Agent": "Mozilla/5.0"})
response.raise_for_status()
except requests.exceptions.RequestException as e:
print(f"Errore nel caricamento della pagina: {e}")
return
soup = BeautifulSoup(response.text, "html.parser")
# Ottenere tutti i tag img
img_tags = soup.find_all("img")
for index, img in enumerate(img_tags):
img_url = img.get("src") or img.get("data-src") # Considera anche lazy loading
if not img_url:
continue
if img_url.startswith("data:image"): # Gestire immagini Base64
try:
header, encoded = img_url.split(",", 1)
img_data = base64.b64decode(encoded)
ext = header.split("/")[1].split(";")[0] # Estrai l'estensione dell'immagine
if ext == "svg+xml":
ext = "png" # Convertire SVG in PNG
img_name = os.path.join(folder, f"base64_image_{index}.{ext}")
with open(img_name, "wb") as img_file:
img_file.write(img_data)
print(f"Scaricata immagine Base64 convertita in PNG: {img_name}")
else:
img_name = os.path.join(folder, f"base64_image_{index}.{ext}")
with open(img_name, "wb") as img_file:
img_file.write(img_data)
print(f"Scaricata immagine Base64: {img_name}")
except Exception as e:
print(f"Errore nella conversione Base64: {e}")
continue
# Convertire URL relativi in assoluti
img_url = urljoin(url, img_url)
img_url = unquote(img_url.split('?')[0]) # Rimuovere parametri dall'URL
try:
img_response = requests.get(img_url, headers={"User-Agent": "Mozilla/5.0"})
img_response.raise_for_status()
img_name = os.path.join(folder, os.path.basename(urlparse(img_url).path))
# Salvare l'immagine
with open(img_name, "wb") as img_file:
img_file.write(img_response.content)
print(f"Scaricata: {img_name}")
except requests.exceptions.RequestException as e:
print(f"Errore nel download di {img_url}: {e}")
if __name__ == "__main__":
while True:
url = input("Inserisci l'URL della pagina web: ")
download_images(url)
scelta = input("\nUtilizza di nuovo lo script digitando 1 o premi 0 per ritornare a main.py: ").strip()
if scelta == '1':
continue
elif scelta == '0':
break
else:
print("Scelta non valida. Inserire 1 o 0.")