first commit

This commit is contained in:
2026-09-11 16:39:17 +03:00
parent 4dd137dc09
commit 07dbd51547
+19 -8
View File
@@ -1,23 +1,21 @@
import mimetypes
import os import os
import requests import requests
from urllib.parse import unquote, urlparse from urllib.parse import unquote, urlparse
# Список URL для скачивания
URL_LIST = [ URL_LIST = [
"https://example.com/sample.pdf", "https://example.com/sample.pdf",
"https://example.com/image.png", "https://example.com/image.png",
] ]
# Папка для сохранения # Изменено назначение папки
SAVE_DIR = "/dw" SAVE_DIR = "/dws"
def download_files(urls, destination_folder): def download_files_with_mimetype(urls, destination_folder):
# Создаем папку, если она не существует
os.makedirs(destination_folder, exist_ok=True) os.makedirs(destination_folder, exist_ok=True)
for url in urls: for url in urls:
# Извлекаем имя файла из URL
parsed_url = urlparse(url) parsed_url = urlparse(url)
filename = os.path.basename(unquote(parsed_url.path)) or "downloaded_file" filename = os.path.basename(unquote(parsed_url.path)) or "downloaded_file"
save_path = os.path.join(destination_folder, filename) save_path = os.path.join(destination_folder, filename)
@@ -26,14 +24,27 @@ def download_files(urls, destination_folder):
response = requests.get(url, stream=True, timeout=15) response = requests.get(url, stream=True, timeout=15)
response.raise_for_status() response.raise_for_status()
# 1. Детект MIME-type из заголовков ответа
content_type = response.headers.get("Content-Type")
# 2. Если заголовок отсутствует/обобщен, определяем по расширению файла
if not content_type or "octet-stream" in content_type:
guessed_type, _ = mimetypes.guess_type(filename)
content_type = guessed_type or "unknown/octet-stream"
# Выводим чистый MIME-type без дополнительных параметров (например, без charset)
clean_mime = content_type.split(";")[0].strip()
with open(save_path, "wb") as f: with open(save_path, "wb") as f:
for chunk in response.iter_content(chunk_size=8192): for chunk in response.iter_content(chunk_size=8192):
f.write(chunk) f.write(chunk)
print(f"Сохранен: {save_path}") # Вывод результата и MIME-типа в консоль
print(f"Сохранен: {save_path} | MIME-type: {clean_mime}")
except Exception as e: except Exception as e:
print(f"Ошибка при скачивании {url}: {e}") print(f"Ошибка при скачивании {url}: {e}")
if __name__ == "__main__": if __name__ == "__main__":
download_files(URL_LIST, SAVE_DIR) download_files_with_mimetype(URL_LIST, SAVE_DIR)