url = <span style="color: #800000">'<span style="color: #800000">http://imgsrc.baidu.com/forum/w%3D580%3B/sign=749ed018cecec3fd8b3ea77de6b3d63f/83025aafa40f4bfb3661b3800e4f78f0f63618b4.jpg<span style="color: #800000">'<span style="color: #000000">
root_path = r<span style="color: #800000">'<span style="color: #800000">D:picturezhaoliying<span style="color: #800000">'
<span style="color: #008000">#<span style="color: #008000">利用split()函数获取url最后的文件名
img_name = url.split(<span style="color: #800000">'<span style="color: #800000">/<span style="color: #800000">')[-1<span style="color: #000000">]
img_path = root_path + r<span style="color: #800000">'<span style="color: #800000">{0}<span style="color: #800000">'<span style="color: #000000">.format(img_name)
<span style="color: #0000ff">try<span style="color: #000000">: #如果根目录不存在就创建该根目录
<span style="color: #0000ff">if <span style="color: #0000ff">not<span style="color: #000000"> os.path.exists(root_path):
os.makedirs(root_path)
</span><span style="color: #0000ff">if</span> <span style="color: #0000ff">not</span><span style="color: #000000"> os.path.exists(img_path):
r </span>=<span style="color: #000000"> requests.get(url)
with open(img_path,</span><span style="color: #800000">'</span><span style="color: #800000">wb</span><span style="color: #800000">'</span><span style="color: #000000">) as f:
f.write(r.content)
f.close()
</span><span style="color: #0000ff">print</span>(<span style="color: #800000">"</span><span style="color: #800000">文件保存成功</span><span style="color: #800000">"</span><span style="color: #000000">)
</span><span style="color: #0000ff">else</span><span style="color: #000000">:
</span><span style="color: #0000ff">print</span>(<span style="color: #800000">"</span><span style="color: #800000">文件已存在</span><span style="color: #800000">"</span><span style="color: #000000">)
<span style="color: #0000ff">except<span style="color: #000000">:
<span style="color: #0000ff">print(<span style="color: #800000">"<span style="color: #800000">执行出错<span style="color: #800000">")-----------------------------------------------------------------输出结果:文件保存成功[Finished in 0.5s]