How to compile Python code for capturing Web Images

Source: Internet
Author: User

Using the Python programming language to capture web content is a common programming technology. Today, we will introduce you in detail how to capture Web Images Using Python, so that you can get some help in practical applications.

Python web image capture code example:

 
 
  1. ImgDownloader  
  2. import win32com.client,time,win32inet,win32file,os  
  3. class ImgDownloader:  
  4. def __init__(self,url,dir):  
  5. self.__dir=dir  
  6. self.__ie=win32com.client.Dispatch('InternetExplorer.Application')  
  7. self.__ie.Navigate(url)  
  8. self.__wait__()  
  9. def __wait__(self):  
  10. while self.__ie.Busy:  
  11. time.sleep(0.1)  
  12. def start(self):  
  13. self.__wait__()  
  14. imgs=self.__ie.Document.getElementsByTagName('img')  
  15. for i in range(imgs.length):  
  16. try:  
  17. cachInfo=win32inet.GetUrlCacheEntryInfo(imgs[i].src)  
  18. if cachInfo:  
  19. path=cachInfo['LocalFileName']  
  20. pathpathinfo=path.split('\\')  
  21. pathinfo.reverse()  
  22. filename=('[%d]' % i) + pathinfo[0]  
  23. win32file.CopyFile(path,os.path.join(self.__dir,filename),True)  
  24. except:  
  25. pass  
  26. def close(self):  
  27. self.__ie.Quit()  
  28. if __name__=='__main__':  
  29. d=ImgDownloader('http://image.baidu.com/i?ct=201326592&cl=2&
    lm=-1&tn=baiduimage&pv=&word=boy&z=0','c:\\temp\\')  
  30. d.start()  
  31. d.close() 

Principle: Use the com interface in Python to run IE browser, open the webpage, obtain the URLs of all images on the webpage, and use the win32api function GetUrlCacheEntryInfo to find the corresponding local cache file of the image and copy it to the specified directory.

The above is how we use Python to capture web images.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.