您当前的位置: 首页 >  Xavier Jiezou Python

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

Xavier Jiezou 发布时间:2020-09-24 17:44:14 ,浏览量:4

写在前面

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

依赖模块

pip3 install requests

下载图片

测试样例

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

源码发布

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

关注
打赏
查看更多评论

Xavier Jiezou

暂无认证

  • 4浏览

    0关注

    358博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文
立即登录/注册

微信扫码登录