import mimetypes import os import requests from urllib.parse import unquote, urlparse URL_LIST = [ "https://example.com/sample.pdf", "https://example.com/image.png", ] # Изменено назначение папки SAVE_DIR = "/dws" def download_files_with_mimetype(urls, destination_folder): os.makedirs(destination_folder, exist_ok=True) for url in urls: parsed_url = urlparse(url) filename = os.path.basename(unquote(parsed_url.path)) or "downloaded_file" save_path = os.path.join(destination_folder, filename) try: response = requests.get(url, stream=True, timeout=15) 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: for chunk in response.iter_content(chunk_size=8192): f.write(chunk) # Вывод результата и MIME-типа в консоль print(f"Сохранен: {save_path} | MIME-type: {clean_mime}") except Exception as e: print(f"Ошибка при скачивании {url}: {e}") if __name__ == "__main__": download_files_with_mimetype(URL_LIST, SAVE_DIR)