【python爬虫】根据url下载图片或视频到本地

写在前面

我们利用python爬虫技术获取到了图片或视频的url直链,那么如何根据url来下载图片或视频。图片是小文件,大小一般在5MB以内,我们直接下载即可。视频是大文件,大小一般在100MB以上,所以建议采用分块下载的方法,避免内存溢出。

安装依赖

pip3 install requests

下载图片

测试样例

https://img-blog.csdnimg.cn/20200924162143340.jpg

ひさぎ-pixiv-76409757

源码发布

import requests
url = 'https://img-blog.csdnimg.cn/20200924162143340.jpg'
res = requests.get(url)
with open('test.jpg', 'wb') as f:
    f.write(res.content)

下载视频

测试样例

https://vkceyugu.cdn.bspapp.com/VKCEYUGU-learning-vue/52eec590-aecd-11ea-b244-a9f5e5565f30.mp4

源码发布

import requests
url = 'https://vkceyugu.cdn.bspapp.com/VKCEYUGU-learning-vue/52eec590-aecd-11ea-b244-a9f5e5565f30.mp4'
res = requests.get(url, stream=True)
with open('test.mp4', 'wb') as f:
    for chunk in res.iter_content(chunk_size=10240):
        f.write(chunk)

参数说明

参数描述
stream默认为False,请求大文件一般设置为True,避免内存溢出
chunk_size分块下载的大小,可以根据需要任意自行调整

温馨提示

超大文件,比如Windows系统等,一般都在4GB以上,这时最好采用本文中分块下载的方法,避免内存溢出。

引用参考

https://requests.readthedocs.io/zh_CN/latest/user/quickstart.html#id5
原文地址:https://www.cnblogs.com/ghgxj/p/14219140.html