第一周单元3:Requests库网络爬虫实例下载图片-split

获取用户输入的文件名

# coding:utf-8
import requests
import os

path = "D:\pic\{}.jpg".format(input("请输入文件名:"))
url = "http://img.mp.itc.cn/upload/20160902/7cf52148ebbc4f378f5d55349bab6429_th.jpg"


try:
    r = requests.get(url)
    r.raise_for_status()
    r.encoding = r.apparent_encoding
    with open(path, 'wb') as f:
        f.write(r.content)
        f.close()
        print("图片保存成功")
except:
    print("Error")

判断目标目录是否存在,不存在则创建,并按原文件名保存

# coding:utf-8
import requests
import os

doc = "D:\pic\"
url = "http://img.mp.itc.cn/upload/20160902/7cf52148ebbc4f378f5d55349bab6429_th.jpg"
Path = doc + url.split("/")[-1]     # 以“/”从最后一个字母向前分割url字符串

try:
    if not os.path.exists(doc):     # 若不加这句,执行报错
       os.mkdir(doc)                # 若文件夹不存在,则创建
    if not os.path.exists(Path):
        r = requests.get(url)
        r.raise_for_status()
        r.encoding = r.apparent_encoding
        with open(Path, 'wb') as f:
            f.write(r.content)
            f.close()
            print("图片保存成功")
    else:
        print("文件名已存在")
except:
    print("Error")
原文地址:https://www.cnblogs.com/p36606jp/p/15113881.html