前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Python下载图片并保存本地的两种方式

Python下载图片并保存本地的两种方式

作者头像
py3study
发布2020-01-08 16:29:23
8.8K0
发布2020-01-08 16:29:23
举报
文章被收录于专栏:python3python3python3

一:使用Python中的urllib类中的urlretrieve()函数,直接从网上下载资源到本地,具体代码:

import os,stat
import urllib.request

img_url="https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1516371301&di=d99af0828bb301fea27c2149a7070" \
        "d44&imgtype=jpg&er=1&src=http%3A%2F%2Fupload.qianhuaweb.com%2F2017%2F0718%2F1500369506683.jpg"
file_path='D:/book/img'
file_name ="pyt"

try:
    #是否有这个路径
    if not os.path.exists(file_path):
    #创建路径
        os.makedirs(file_path)
        #获得图片后缀
    file_suffix = os.path.splitext(img_url)[1]
    print(file_suffix)
        #拼接图片名(包含路径)
    filename = '{}{}{}{}'.format(file_path,os.sep,file_name,file_suffix)
    print(filename)
       #下载图片,并保存到文件夹中
    urllib.request.urlretrieve(img_url,filename=filename)

except IOError as e:
    print("IOError")
except Exception as e:
    print("Exception")

二:利用读写操作写入文件,具体代码:

import os,stat
import urllib.request

for i in range(1,3):
    if not os.path.exists("./rym"):
        print("不纯在")
        os.makedirs("./rym")

    else:
        print("存在")
        os.chmod("D:/imagss",777)


        with urllib.request.urlopen("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1516371301&di=d99af0828b"
                                    "b301fea27c2149a7070d44&imgtype=jpg&er=1&src=http%3A%2F%2Fupload.qianhuaweb.com%2F2017%2F0718%"
                                    "2F1500369506683.jpg", timeout=30) as response, open("./rym/lyj.png"
                , 'wb') as f_save:
            f_save.write(response.read())
            f_save.flush()
            f_save.close()
            print("成功")
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019-09-02 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档