- 打卡等级:初来乍到
- 打卡总天数:6
- 打卡月天数:6
- 打卡总奖励:157
- 最近打卡:2024-11-20 10:22:49
管理员
BSAY论坛创始人
- 积分
- 400190
|
- import os
- import requests
- from concurrent.futures import ThreadPoolExecutor, as_completed
- # 壁纸文件夹路径
- wallpaper_folder = r"E:\download\testimg"
- os.makedirs(wallpaper_folder, exist_ok=True)
- # 失败图片链接存储文件路径
- failed_urls_file = r"E:\download\testimg\shibai.txt"
- # 读取img.txt文件中的图片链接
- with open(r"E:\download\testimg\img.txt", "r") as file:
- image_urls = file.readlines()
- def download_image(url):
- url = url.strip() # 去除首尾空白字符
- try:
- response = requests.get(url, timeout=120)
- response.raise_for_status()
- # 提取图片文件名
- filename = os.path.basename(url)
- # 保存图片至壁纸文件夹
- with open(os.path.join(wallpaper_folder, filename), "wb") as img_file:
- img_file.write(response.content)
- print(f"已下载图片: {filename}")
- except requests.exceptions.RequestException as e:
- print(f"图片下载失败: {e}")
- with open(failed_urls_file, "a") as failed_urls:
- failed_urls.write(url + "\n")
- # 清空失败图片链接文件
- open(failed_urls_file, "w").close()
- # 批量下载图片(多线程异步)
- with ThreadPoolExecutor() as executor:
- futures = [executor.submit(download_image, url) for url in image_urls]
- for future in as_completed(futures):
- try:
- future.result()
- except Exception as e:
- print(f"图片下载失败: {e}")
- print("图片下载完成!")
复制代码- 壁纸文件夹路径(下载后,文件的存放路径)
- 失败图片链接存储文件路径
- 读取img.txt文件中的图片链接(文件链接,一行一个)
- 以上都弄好了,直接执行 python batchImg.py 即可
|
|