import os
import time
import requests
import threading
import aiohttp
import asyncio
# 图片下载地址列表
url_list = [
"http://kr.shanghai-jiuxin.com/file/2021/0130/6febfd0f5c582812652b596b9ed161cc.jpg",
"http://kr.shanghai-jiuxin.com/file/2021/0127/d9632ca87f6092ade704088e5883f9d9.jpg",
"http://kr.shanghai-jiuxin.com/file/2021/0127/a0929a01581fbc27d564bd2baef5f905.jpg",
"http://kr.shanghai-jiuxin.com/file/2021/0127/78cfa4047cfdf5cd75255f2cf32b3db5.jpg",
"http://kr.shanghai-jiuxin.com/file/2021/0127/83233215c2d889993b511d518a638cef.jpg",
"http://kr.shanghai-jiuxin.com/file/2021/0127/ec0f2d3e632ba7eb788a0d47cb2c9c2a.jpg",
"http://kr.shanghai-jiuxin.com/file/2021/0127/6f7d15a6ab5b9e9cb8aa522c35bca6e4.jpg",
"http://kr.shanghai-jiuxin.com/file/2021/0309/3a873157c74a273fa9fccd09ba4b321a.jpg",
"http://kr.shanghai-jiuxin.com/file/2021/0309/533f4566f4ad8698f4c8ad48358705c7.jpg",
"http://kr.shanghai-jiuxin.com/file/2021/0309/010fbe278a27db9ce88da9689b198d29.jpg",
"http://kr.shanghai-jiuxin.com/file/2021/0309/a69900581e267e9aab4041e777a8e339.jpg"
]
"""在当前目录下创建文件夹用于存放图片"""
if not os.path.exists("pictures"):
os.makedirs("pictures")
"""单线程"""
start_time = time.time()
for url in url_list:
name = url.split("/")[-1] # 切取url中的信息作为图片的名称
resp = requests.get(url).content
with open(file="./pictures/{name}".format(name=name), mode="wb") as file:
file.write(resp)
print("共计用时:{}".format(time.time() - start_time))
"""多线程"""
def download(url):
name = url.split("/")[-1] # 切取url中的信息作为图片的名称
resp = requests.get(url).content
with open(file="./pictures/{name}".format(name=name), mode="wb") as file:
file.write(resp)
start_time = time.time()
for url in url_list:
threading.Thread(target=download, args=(url, )).start()
time.sleep(0.5)
print("共计用时:{}".format(time.time() - start_time))
"""协程"""
async def fetch(url):
async with aiohttp.ClientSession() as session:
async with session.get(url) as resp:
content = await resp.content.read()
name = url.split("/")[-1]
with open(file="./pictures/{name}".format(name=name), mode="wb") as file:
file.write(content)
async def main():
start_time = time.time()
tasks = []
for url in url_list:
tasks.append(asyncio.create_task(fetch(url)))
await asyncio.wait(tasks)
print("共计用时:{}".format(time.time() - start_time))
asyncio.run(main())
网友评论