In [1]:
import urllib2
import httplib
import requests
In [ ]:
response = requests.get("http://fb.me/4FiCLm7fx", timeout=10)
response.url
Out[ ]:
In [2]:
TESTING_URL="http://gvwy.io/alh1b4o"
In [3]:
response = urllib2.urlopen("http://bit.ly/AoifeMcL_ID3") # Some shortened url
response.url
Out[3]:
In [4]:
opener = urllib2.build_opener()
opener.addheaders = [('User-Agent', 'Mozilla/5.0')]
response = opener.open('http://fb.me/7z2JmTFOc')
response.url
Out[4]:
In [5]:
opener.handlers
Out[5]:
In [6]:
try:
response = opener.open('http://fb.me/7z2JmTFOc', timeout=100)
response.url
except urllib2.HTTPError as e:
print "HTTPError"
print e
except urllib2.URLError as e:
print "URLError"
print e
except Exception as e:
print "Other exception"
print e
print response.url
In [7]:
class SmartRedirectHandler(urllib2.HTTPRedirectHandler):
def http_error_301(self, req, fp, code, msg, headers):
print "Error 301"
print headers
result = urllib2.HTTPRedirectHandler.http_error_301(
self, req, fp, code, msg, headers)
result.status = code
result.extra_headers = headers
return result
def http_error_302(self, req, fp, code, msg, headers):
print "Error 302"
print headers
result = urllib2.HTTPRedirectHandler.http_error_302(
self, req, fp, code, msg, headers)
result.status = code
return result
In [8]:
opener = urllib2.build_opener(SmartRedirectHandler)
opener.addheaders = [('User-Agent', 'Mozilla/5.0')]
response = opener.open('http://fb.me/7z2JmTFOc')
response.url
Out[8]:
In [9]:
response.extra_headers["LOCATION"]
Out[9]:
In [10]:
response.org_loc = 10
In [11]:
opener.handlers
Out[11]:
In [13]:
response = requests.get('http://fb.me/7z2JmTFOc')
In [14]:
response.url
Out[14]:
In [15]:
response.history[0].headers["Location"]
Out[15]:
In [16]:
try:
response = requests.get(TESTING_URL, timeout=10)
except requests.RequestException as e:
print e
In [17]:
e.request.url
Out[17]:
In [18]:
try:
e = None
a = None
a.append(1)
except IndexError as e:
print e, type(e)
except Exception as e:
print "General exp block"
print e, type(e)
else:
print "Else block"
print e, type(e)
In [19]:
response = requests.get("http://fb.me/7z2JmTFOc")
response.url
Out[19]:
In [21]:
TESTING_URL = "http://fb.me/PeRMrk16"
try:
response = requests.get(TESTING_URL, timeout=10)
except requests.RequestException as e:
print e
In [22]:
e.request.url
Out[22]:
In [ ]: