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

yipeiwu_com5年前Python基础

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

import os,stat
import urllib.request
 
img_url="/zb_users/upload/202003/0x41dwks31d.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("/zb_users/upload/202003/nra3dfwwl5l.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下载图片并保存本地的两种方式详解整合,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对【听图阁-专注于Python设计】网站的支持!

相关文章

在Python中等距取出一个数组其中n个数的实现方式

在Python中等距取出一个数组其中n个数的实现方式

应用场景: 实验中不断得到新数据,想将数据图形化,但随着时间推移,数据越来越多, 此时需要我们等距选择数据列表中固定数量的数据,来进行图形化。 注:保留首尾数据。 import nu...

python使用 zip 同时迭代多个序列示例

本文实例讲述了python使用 zip 同时迭代多个序列。分享给大家供大家参考,具体如下: zip 可以平行地遍历多个迭代器 python 3中zip相当于生成器,遍历过程中产生元祖,p...

Python三级菜单的实例

要求: 打印省、市、县三级菜单 可返回上一级 可随时退出程序 版本1 # _author : Ahern Li # @_date : 2017/9/12 menu = { '浙...

Python 异常处理的实例详解

Python 异常处理的实例详解 与许多面向对象语言一样,Python 具有异常处理,通过使用 try...except 块来实现。 Note: Python v s. Java 的异常...

python启动办公软件进程(word、excel、ppt、以及wps的et、wps、wpp)

复制代码 代码如下:#-*- coding:utf-8 -*- from win32com.client import Dispatch import time def start_of...