利用Python编程语言进行网页内容的抓取是一个比较常用的编程技术。那么,今天我们将会为大家详细介绍一下有关Python抓取网页图片的操作方法,以方便大家在实际应用中获得一些帮助。

创新互联科技有限公司专业互联网基础服务商,为您提供成都移动机房托管,高防物理服务器租用,成都IDC机房托管,成都主机托管等互联网服务。
Python抓取网页图片代码示例:
- 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浏览器,然后打开网页,获取网页所有图片的URL,最后利用win32api函数GetUrlCacheEntryInfo找出图片相应的本地缓存文件,复制到指定目录。
以上就是我们为大家介绍的Python抓取网页图片的应用方式。