Advertisement
Guest User

Untitled

a guest
Oct 4th, 2017
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.83 KB | None | 0 0
  1. import Image
  2. import sys
  3. import os
  4. from BeautifulSoup import BeautifulSoup as bs
  5. import urlparse
  6. from urllib2 import *
  7. from urllib import urlretrieve
  8.  
  9.  
  10. class Ysi(object):
  11. def __init__(self):
  12. self.soup = ""
  13. self.out_folder = "/tmp"
  14.  
  15.  
  16. """ Get picture from the Internet """
  17. def get_picture(self, url, username="", password=""):
  18. try:
  19. self.soup = bs(urlopen(url))
  20. except IOError, e:
  21. if not hasattr(e, 'code') or e.code != 401:
  22. print "This page isn't protected by authentication."
  23. print 'But we failed for another reason.'
  24. sys.exit(1)
  25. # If error was caused by authentication, try to authenticate
  26. self.__handle_page_authentication(url, username, password)
  27.  
  28. parsed = list(urlparse.urlparse(url))
  29.  
  30. for image in self.soup.findAll("img"):
  31. print "Image: %(src)s" % image
  32. filename = image["src"].split("/")[-1]
  33. parsed[2] = image["src"]
  34. outpath = os.path.join(self.out_folder, filename)
  35.  
  36. if image["src"].lower().startswith("http"):
  37. urlretrieve(image["src"], outpath)
  38. else:
  39. urlretrieve(urlparse.urlunparse(parsed), outpath)
  40.  
  41. ''' this causing a error'''
  42. self.im = Image.open(image)
  43.  
  44.  
  45. """ Handle possible authentication """
  46. def __handle_page_authentication(self, url, username, password):
  47. passman = HTTPPasswordMgrWithDefaultRealm()
  48. passman.add_password(None, url, username, password)
  49. authhandler = HTTPBasicAuthHandler(passman)
  50. opener = build_opener(authhandler)
  51. install_opener(opener)
  52. self.soup = bs(urlopen(url))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement