python爬蟲-下載圖片到本地目錄

import requests
import os
url = "https://ss0.bdstatic.com/5aV1bjqh_Q23odCf/static/superman/img/logo/bd_logo1_31bdc765.png"
root = "F://python//"
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)
        r.raise_for_status()
        #使用with語句可以不用自己手動關閉已經打開的文件流
        with open(path,"wb") as f: #開始寫文件,wb代表寫二進制文件
            f.write(r.content)
        print("爬取完成")
    else:
        print("文件已存在")
except Exception as e:
    print("爬取失敗:"+str(e))
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章