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() 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()
max_concurrent_threads = 10 with concurrent.futures.ThreadPoolExecutor(max_concurrent_threads) as executor: executor.map(download_image, img_urls)
print("所有图片下载完成")
|