# 使用多线程下载图片
import os.path
from concurrent.futures import ThreadPoolExecutor
from urllib.request import urlopen,Request
def img_download(url: str):
new_url = Request(url,headers={"User-Agent":"Mozilla/5.0"})
with urlopen(new_url) as web_site:
img_data = web_site.read()
if not img_data:
raise Exception("error:img cannot download!!")
file_name = os.path.basename(url)
with open(file_name,"wb") as file:
file.write(img_data)
return f"img download successfully,{url}"
with ThreadPoolExecutor() as executor:
urls = [
"https://www.aishry.com/media/20221108/202211081443277K.jpg",
"https://www.aishry.com/media/20240106/20240106020531aM.jpg",
"https://www.aishry.com/media/20230803/202308032336387p.jpg",
"https://www.aishry.com/media/20240106/202401060140372F.jpg",
"https://www.aishry.com/media/20240106/202401060159118t.jpg"
]
results = executor.map(img_download,urls)
for res in results:
print(res)
python 线程池例子
最新推荐文章于 2024-07-12 16:16:27 发布