Python抓取網(wǎng)頁圖片相關代碼編寫方法
作者:佚名
我們今天將會通過對一段代碼的解讀來為大家詳細介紹一下Python抓取網(wǎng)頁圖片的相關操作方法,希望大家可以從中掌握這一應用技術。
利用Python編程語言進行網(wǎng)頁內(nèi)容的抓取是一個比較常用的編程技術。那么,今天我們將會為大家詳細介紹一下有關Python抓取網(wǎng)頁圖片的操作方法,以方便大家在實際應用中獲得一些幫助。
Python抓取網(wǎng)頁圖片代碼示例:
- ImgDownloader
- import win32com.client,time,win32inet,win32file,os
- class ImgDownloader:
- def __init__(self,url,dir):
- self.__dir=dir
- self.__ie=win32com.client.Dispatch('InternetExplorer.Application')
- self.__ie.Navigate(url)
- self.__wait__()
- def __wait__(self):
- while self.__ie.Busy:
- time.sleep(0.1)
- def start(self):
- self.__wait__()
- imgs=self.__ie.Document.getElementsByTagName('img')
- for i in range(imgs.length):
- try:
- cachInfo=win32inet.GetUrlCacheEntryInfo(imgs[i].src)
- if cachInfo:
- path=cachInfo['LocalFileName']
- pathpathinfo=path.split('\\')
- pathinfo.reverse()
- filename=('[%d]' % i) + pathinfo[0]
- win32file.CopyFile(path,os.path.join(self.__dir,filename),True)
- except:
- pass
- def close(self):
- self.__ie.Quit()
- if __name__=='__main__':
- d=ImgDownloader('http://image.baidu.com/i?ct=201326592&cl=2&
lm=-1&tn=baiduimage&pv=&word=boy&z=0','c:\\temp\\')- d.start()
- d.close()
原理:在Python使用com 接口運行IE瀏覽器,然后打開網(wǎng)頁,獲取網(wǎng)頁所有圖片的URL,最后利用win32api函數(shù)GetUrlCacheEntryInfo找出圖片相應的本地緩存文件,復制到指定目錄。
以上就是我們?yōu)榇蠹医榻B的Python抓取網(wǎng)頁圖片的應用方式。
【編輯推薦】
責任編輯:曹凱
來源:
博客園