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

发布时间:2020-10-22 16:07:13 作者:丿Somnus丨灬祭月
来源:脚本之家 阅读:210

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

import os,stat
import urllib.request
 
img_url="https://cache.yisu.com/upload/information/20200622/113/35258.html"
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://cache.yisu.com/upload/information/20200622/113/35259.html", timeout=30) as response, open("./rym/lyj.png"
    , 'wb') as f_save:
   f_save.write(response.read())
   f_save.flush()
   f_save.close()
   print("成功")

以上所述是小编给大家介绍的Python下载图片并保存本地的两种方式详解整合,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对亿速云网站的支持!

推荐阅读:
  1. php获取远程网站图片并保存本地
  2. php获取图片并保存到本地的方法

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

python 下载图片 保存

上一篇:css实现两栏布局的方法有哪些

下一篇:Android 使用AlarmManager和NotificationManager来实现闹钟和通知栏

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》