目标:使用协程实现网络图片下载
思路:
1.根据url地址请求网络资源
2.在本地创建文件准备保存
3.读取网络资源数据
4.把读取的网络资源写入到本地文件中
5.做异常捕获
代码:
单线程下载:
import urllib
def download_img(imgUrl, fileName):
# 根据url请求网络资源
response_data = urllib.request.urlopen(imgUrl)
# 在本地创建文件,准备保存
with open(fileName, "wb") as file:
while True:
# 读取网络资源
file_data = response_data.read(1024)
# 判断读取的数据是否为空,不为空继续写,为则表示已经读到文件末尾,需跳出循环
if file_data:
# 写入本地文件
file.write(file_data)
else:
break
def main():
# 要下载图片的路径
img1Url = "https://www.qqpao.com/uploads/allimg/181116/10-1Q116102128.gif"
img2Url = "https://uploadfile.huiyi8.com/2014/1107/20141107114402602.gif"
img3Url = "https://media1.giphy.com/media/l41lXnhesd96Aa9os/giphy.gif"
download_img(img1Url,"C:/Users/Desktop/1.gif")
download_img(img2Url, "C:/Users/Desktop/2.gif")
download_img(img3Url, "C:/Users/Desktop/3.gif")
if __name__ == '__main__':
main()
使用协程实现并发下载:
import urllib,gevent,requests
from gevent import monkey
monkey.patch_all()
def download_img(imgUrl, fileName):
try:
# 根据url请求网络资源
response_data = urllib.request.urlopen(imgUrl)
# 在本地创建文件,准备保存
with open(fileName, "wb") as file:
while True:
# 读取网络资源
file_data = response_data.read(1024)
# 判断读取的数据是否为空,不为空继续写,为则表示已经读到文件末尾,需跳出循环
if file_data:
# 写入本地文件
file.write(file_data)
else:
break
except Exception as e:
print("文件 %s 下载失败! %s" % (fileName,e))
else:
print("文件 %s 下载成功!" % (fileName))
def main():
# 要下载图片的路径
img1Url = "https://www.qqpao.com/uploads/allimg/181116/10-1Q116102128.gif"
img2Url = "https://uploadfile.huiyi8.com/2014/1107/20141107114402602.gif"
img3Url = "https://media1.giphy.com/media/l41lXnhesd96Aa9os/giphy.gif"
gevent.joinall([
gevent.spawn(download_img, img1Url, "C:/Users/Desktop/1.gif"),
gevent.spawn(download_img, img2Url, "C:/Users/Desktop/2.gif"),
gevent.spawn(download_img, img3Url, "C:/Users/Desktop/3.gif"),
])
if __name__ == '__main__':
main()