欢迎来到代码驿站!

Python代码

当前位置:首页 > 软件编程 > Python代码

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

时间:2021-04-01 08:17:12|栏目:Python代码|点击:

一:使用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("成功")

上一篇:Python中浅拷贝copy与深拷贝deepcopy的简单理解

栏    目:Python代码

下一篇:python转化excel数字日期为标准日期操作

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

本文地址:http://www.codeinn.net/misctech/92116.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有