再進行python編碼過程中,需要對網站上圖片進行下載保存到本地,以下實例實現將指定的圖片下載保存到本地:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
'''
@author:freesigefei
Created on 2016年3月11日
'''
#本模塊作用爲通過直接訪問圖片下載地址,直接將圖片下載保存到本地
import os,urllib
#首先定義圖片下載的網址,以及圖片本地保存的文件夾地址
urlPath='http://192.168.1.1/logo'
#根據文件名創建文件
def createFileWithFileName(localPathParam,fileName):
'''根據文件名創建文件,localPathParam保存的本地路徑,fileName保存的文件名'''
totalPath=localPathParam+fileName
if not os.path.exists(totalPath):
Image_file=open(totalPath,'a+')
Image_file.close()
return totalPath
#根據圖片的地址,下載圖片並保存在本地
def getAndSaveImg(imgUrl,fileName):
'''將下載的圖片保存到本地,imgUrl表示下載地址,fileName表示保存的文件名'''
localPath='D:\\download\\' #localPath表示保存的本地路徑
if( len(imgUrl)!= 0 ):
urllib.urlretrieve(imgUrl,createFileWithFileName(localPath,fileName))
if __name__ == '__main__':
getAndSaveImg(urlPath,'Logo.jpg')
通過運行本實例,可以將對應地址的logo圖片下載到本地目錄下