python爬蟲入門---第三篇:保存一張圖片


import requests
import os


url = 'http://imgsrc.baidu.com/forum/w%3D580%3B/sign=749ed018cecec3fd8b3ea77de6b3d63f/83025aafa40f4bfb3661b3800e4f78f0f63618b4.jpg'
root_path = r'D:\picture\zhaoliying'

#利用split()函數獲取url最后的文件名
img_name = url.split('/')[-1]

img_path = root_path + r'\{0}'.format(img_name)

try:
  #如果根目錄不存在就創建該根目錄
if not os.path.exists(root_path): os.makedirs(root_path) if not os.path.exists(img_path): r = requests.get(url) with open(img_path, 'wb') as f: f.write(r.content) f.close() print("文件保存成功") else: print("文件已存在") except: print("執行出錯")

-----------------------------------------------------------------
輸出結果:
文件保存成功
[Finished in 0.5s]

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM