网络图片的爬取和存储.py(亲测有效)

import requests
import os

url = "https://ss0.baidu.com/7Po3dSag_xI4khGko9WTAnF6hhy/zhidao/pic/item/9c16fdfaaf51f3de9ba8ee1194eef01f3a2979a8.jpg"  # 图片的url
root = "D://桌面//pics//"   # 以原图片名字命名
path = root + url.split('/')[-1]

# path1= "D://桌面//pics//abc.jpg"  # 自定义命名
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("获取失败")
原文地址:https://www.cnblogs.com/qianmo123/p/14213457.html