python的requests庫-圖片保存

將圖片保存爲指定名稱

import requests
path = "D://abc.jpg"
url = "http://image.ngchina.com.cn/2020/0522/20200522102949447.jpg"
r = requests.get(url)
r.status_code
with open(path, "wb") as f:
    f.write(r.content)
f.close

將圖片保存爲原名稱,放入指定文件夾

import requests
import os
root = "D://pics//"
url = "http://image.ngchina.com.cn/2020/0522/20200522102949447.jpg"
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("success")
    else:
        print("exists")
except:
    print("fail")

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章