一:使用python中的urllib类中的urlretrieve()函数,直接从网上下载资源到本地,具体代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
|
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" )
|
二:利用读写操作写入文件,具体代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
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下载图片并保存本地的两种方式详解整合,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对服务器之家网站的支持!
原文链接:https://blog.csdn.net/Pan_YT/article/details/79050961