常用小脚本收集

Python

批量下载

批量下载文件中给定的 urls

假如需要下载的 urls 存在于给定的文件中(每行一个 url),本示例演示批量并发下载,假设 urls 存在于文件 img.txt

import concurrent.futures
import requests

# 创建一个函数来下载图片
def download_image(url):
try:
response = requests.get(url)
response.raise_for_status() # 检查是否有 HTTP 错误
print(f"下载完成: {url}")
except requests.exceptions.RequestException as e:
print(f"下载失败: {url}, 错误: {e}")


# 从文件中读取图片链接
with open("img.txt", "r") as file:
img_urls = file.read().splitlines()

# 使用 ThreadPoolExecutor 来限制并发线程数量为 10
max_concurrent_threads = 10
with concurrent.futures.ThreadPoolExecutor(max_concurrent_threads) as executor:
# 提交任务并下载图片
executor.map(download_image, img_urls)

print("所有图片下载完成")