为什么用这个脚本

分享一个批量通过图片链接下载图片的python脚本,个人感觉还挺好用,就分享一下

当然也有很多第三方工具,不过我找了几个,要么就是很难用,要么就是有广告,或者收费等等,太麻烦,我喜欢直来直去,简单点儿

使用门槛

执行python脚本,肯定是要python环境的,可以参考这篇文章Python 超级详细安装教程(Windows),也不复杂

有些依赖自行百度安装下即可

如何使用

先分享下python源码

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
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即可