網絡爬蟲前奏之圖片的爬取006

import requests
import os
#爬取圖片的url
url = "https://images-cn.ssl-images-amazon.com/images/I/81M5fmmHKbL._AC_SL1500_.jpg"
#圖片存放的目錄
root="E://移動後的桌面//爬蟲//image//"
#圖片存放的目錄加網頁圖片的名字
path=root+url.split('/')[-1]
try:
    #判斷root目錄是不是存在,不存在就創建
    if not os.path.exists(root):
        os.mkdir(root)
    #如果圖片不存在,執行一段代碼
    if not os.path.exists(path):
        #請求
        r=requests.get(url)
        #(wb):以二進制的形式打開文件只用於寫入
        with open(path,'wb') as f:
            把圖片的二進制保存
            f.write(r.content)
            f.close()
            print("文件保存成功")
    else:
        print("文件已經存在")
except:
    print("爬取失敗")

 

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