用python抓取网上的照片并保存在本地(Python经典编程案例)

用python抓取网上的照片并保存在本地

import requests
import os

url = "http://image.nationalgeographic.com.cn/2017/0926/20170926103910736.jpg"
root = "D://pics//"
path = root + url.split('/')[-1]
try:
    if not os.path.exists(root):
        os.mkdir(root)
    if not os.path.exists(path):
        r = requests.get(url)
        with open(path, 'wb') as f:
            f.write(r.content)
            f.close()
            print("文件保存成功")
    else:
        print("文件已存在")
except:
    print("失败")

执行结果如下图所示:
用python抓取网上的照片并保存在本地(Python经典编程案例)_第1张图片
存到本地的照片如下图:

用python抓取网上的照片并保存在本地(Python经典编程案例)_第2张图片

你可能感兴趣的:(python经典编程案例)