1 """Robot based on urllib2
3 This file is a part of Bookmarks database and Internet robot.
7 __author__ = "Oleg Broytman <phd@phdru.name>"
8 __copyright__ = "Copyright (C) 2014-2024 PhiloSoft Design"
9 __license__ = "GNU GPL"
11 __all__ = ['robot_urllib2']
17 from Robots.bkmk_robot_base import robot_base, request_headers, get_error
23 class FTPHandler(urllib2.FTPHandler):
24 def connect_ftp(self, user, passwd, host, port, dirs, timeout):
26 _fw = urllib2.FTPHandler.connect_ftp(self, user, passwd, host, port,
31 opener = urllib2.OpenerDirector()
32 default_classes = [urllib2.HTTPHandler, urllib2.HTTPDefaultErrorHandler,
33 FTPHandler, urllib2.HTTPErrorProcessor]
34 if hasattr(httplib, 'HTTPS'):
35 default_classes.insert(0, urllib2.HTTPSHandler)
36 for klass in default_classes:
37 opener.add_handler(klass())
39 urllib2.install_opener(opener)
42 class robot_urllib2(robot_base):
43 def get(self, bookmark, url, accept_charset=False):
44 request = urllib2.Request(url)
45 for h, v in request_headers.items():
46 request.add_header(h, v)
47 if accept_charset and bookmark.charset:
48 request.add_header('Accept-Charset', bookmark.charset)
54 response = urllib2.urlopen(request)
56 except urllib2.HTTPError as e:
57 if e.code in (301, 302, 303, 307, 308):
58 return None, e.code, e.hdrs['Location'], None, None
60 self.log(' HTTP Error %s: %s' % (e.code, e.msg))
61 return ("HTTP Error %s: %s" % (e.code, e.msg),
62 None, None, None, None)
64 except urllib2.URLError as e:
65 self.log(' URL Error: %s' % e.reason)
66 return "URL Error: %s" % e.reason, None, None, None, None
68 except httplib.HTTPException as e:
70 self.log(' HTTP Exception: %s' % error)
71 return "HTTP Exception: %s" % error, None, None, None, None
75 self.log(' I/O Error: %s' % error)
76 return "I/O Error: %s" % error, None, None, None, None
79 return None, None, None, response.info(), response.read()
81 def get_ftp_welcome(self):
84 return _fw.ftp.welcome