first commit
This commit is contained in:
@@ -1,23 +1,21 @@
|
||||
import mimetypes
|
||||
import os
|
||||
import requests
|
||||
from urllib.parse import unquote, urlparse
|
||||
|
||||
# Список URL для скачивания
|
||||
URL_LIST = [
|
||||
"https://example.com/sample.pdf",
|
||||
"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)
|
||||
|
||||
for url in urls:
|
||||
# Извлекаем имя файла из URL
|
||||
parsed_url = urlparse(url)
|
||||
filename = os.path.basename(unquote(parsed_url.path)) or "downloaded_file"
|
||||
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.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)
|
||||
|
||||
print(f"Сохранен: {save_path}")
|
||||
# Вывод результата и MIME-типа в консоль
|
||||
print(f"Сохранен: {save_path} | MIME-type: {clean_mime}")
|
||||
|
||||
except Exception as e:
|
||||
print(f"Ошибка при скачивании {url}: {e}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
download_files(URL_LIST, SAVE_DIR)
|
||||
download_files_with_mimetype(URL_LIST, SAVE_DIR)
|
||||
Reference in New Issue
Block a user