Urllib2 – the missing manual multinational debit card owned by mastercard

Related articles

You may also find useful the following articles on fetching web

Resources with python :

Basic authentication

A tutorial on basic authentication, with examples in python.

Cookielib and clientcookie

How to handle cookies when fetching web-pages with urllib2.

Urllib2 is a python module for fetching urls

(uniform resource locators). It offers a very simple interface, in the form of

The urlopen function. This is capable of fetching urls using a variety

Of different protocols. It also offers a slightly more complex

Interface for handling common situations – like basic authentication,

Cookies, proxies and so on. These are provided by objects called

Handlers and openers.

Urllib2 supports fetching urls for many URL schemes (identified by the string

multinational debit card owned by mastercard

Before the : in URL – for example ftp is the URL scheme of

Ftp://python.Org/) using their associated network protocols (e.G. FTP, HTTP).

This tutorial focuses on the most common case, HTTP.

For straightforward situations urlopen is very easy to use. But as

Soon as you encounter errors or non-trivial cases when opening HTTP

URLs, you will need some understanding of the hypertext transfer

Protocol. The most comprehensive and authoritative reference to HTTP

Is RFC 2616. This is a technical document and not intended to be

Easy to read. This HOWTO aims to illustrate using urllib2, with

Enough detail about HTTP to help you through. It is not intended to

Replace the urllib2 docs ,

But is supplementary to them.

Import urllib

Import urllib2

Url = ‘http://www.Someserver.Com/cgi-bin/register.Cgi’

multinational debit card owned by mastercard

Values = { ‘name’ : ‘michael foord’ ,

‘location’ : ‘northampton’ ,

‘language’ : ‘python’ }

Data = urllib . Urlencode ( values )

Req = urllib2 . Request ( url , data )

Response = urllib2 . Urlopen ( req )

The page = response . Read ( )

Note that other encodings are sometimes required (e.G. For file upload

From HTML forms – see

HTML specification, form submission

For more details).

If you do not pass the data argument, urllib2 uses a GET

Request. One way in which GET and POST requests differ is that POST

Requests often have side-effects: they change the state of the

System in some way (for example by placing an order with the website

For a hundredweight of tinned spam to be delivered to your door).

Though the HTTP standard makes it clear that posts are intended to

multinational debit card owned by mastercard

Always cause side-effects, and GET requests never to cause

Side-effects, nothing prevents a GET request from having side-effects,

Nor a POST requests from having no side-effects. Data can also be

Passed in an HTTP GET request by encoding it in the URL itself.

This is done as follows.

>>> import urllib2

>>> import urllib

>>> data = {}

>>> data[‘name’] = ‘somebody here’

>>> data[‘location’] = ‘northampton’

>>> data[‘language’] = ‘python’

>>> url values = urllib.Urlencode(data)

>>> print url values


>>> url = ‘http://www.Example.Com/example.Cgi’

>>> full url = url + ‘?’ + url values

>>> data = urllib2.Urlopen(full url)

multinational debit card owned by mastercard

Notice that the full URL is created by adding a ? To the URL, followed by

The encoded values.

# table mapping response codes to messages; entries have the

# form {code: (shortmessage, longmessage)}.

Responses = {

100 : ( ‘continue’ , ‘request received, please continue’ ) ,

101 : ( ‘switching protocols’ ,

‘switching to new protocol; obey upgrade header’ ) ,

200 : ( ‘OK’ , ‘request fulfilled, document follows’ ) ,

201 : ( ‘created’ , ‘document created, URL follows’ ) ,

202 : ( ‘accepted’ ,

‘request accepted, processing continues off-line’ ) ,

203 : ( ‘non-authoritative information’ , ‘request fulfilled from cache’ ) ,

204 : ( ‘no content’ , ‘request fulfilled, nothing follows’ ) ,

205 : ( ‘reset content’ , ‘clear input form for further input.’ ) ,

206 : ( ‘partial content’ , ‘partial content follows.’ ) ,

multinational debit card owned by mastercard

300 : ( ‘multiple choices’ ,

‘object has several resources — see URI list’ ) ,

301 : ( ‘moved permanently’ , ‘object moved permanently — see URI list’ ) ,

302 : ( ‘found’ , ‘object moved temporarily — see URI list’ ) ,

303 : ( ‘see other’ , ‘object moved — see method and URL list’ ) ,

304 : ( ‘not modified’ ,

‘document has not changed since given time’ ) ,

305 : ( ‘use proxy’ ,

‘you must use proxy specified in location to access this ‘

‘resource.’ ) ,

307 : ( ‘temporary redirect’ ,

‘object moved temporarily — see URI list’ ) ,

400 : ( ‘bad request’ ,

‘bad request syntax or unsupported method’ ) ,

401 : ( ‘unauthorized’ ,

‘no permission — see authorization schemes’ ) ,

402 : ( ‘payment required’ ,

‘no payment — see charging schemes’ ) ,

403 : ( ‘forbidden’ ,

multinational debit card owned by mastercard

‘request forbidden — authorization will not help’ ) ,

404 : ( ‘not found’ , ‘nothing matches the given URI’ ) ,

405 : ( ‘method not allowed’ ,

‘specified method is invalid for this server.’ ) ,

406 : ( ‘not acceptable’ , ‘URI not available in preferred format.’ ) ,

407 : ( ‘proxy authentication required’ , ‘you must authenticate with ‘

‘this proxy before proceeding.’ ) ,

408 : ( ‘request timeout’ , ‘request timed out; try again later.’ ) ,

409 : ( ‘conflict’ , ‘request conflict.’ ) ,

410 : ( ‘gone’ ,

‘URI no longer exists and has been permanently removed.’ ) ,

411 : ( ‘length required’ , ‘client must specify content-length.’ ) ,

412 : ( ‘precondition failed’ , ‘precondition in headers is false.’ ) ,

413 : ( ‘request entity too large’ , ‘entity is too large.’ ) ,

multinational debit card owned by mastercard

414 : ( ‘request-URI too long’ , ‘URI is too long.’ ) ,

415 : ( ‘unsupported media type’ , ‘entity body in unsupported format.’ ) ,

416 : ( ‘requested range not satisfiable’ ,

‘cannot satisfy request range.’ ) ,

417 : ( ‘expectation failed’ ,

‘expect condition could not be satisfied.’ ) ,

500 : ( ‘internal server error’ , ‘server got itself in trouble’ ) ,

501 : ( ‘not implemented’ ,

‘server does not support this operation’ ) ,

502 : ( ‘bad gateway’ , ‘invalid responses from another server/proxy.’ ) ,

503 : ( ‘service unavailable’ ,

‘the server cannot process the request due to a high load’ ) ,

504 : ( ‘gateway timeout’ ,

‘the gateway server did not receive a timely response’ ) ,

505 : ( ‘HTTP version not supported’ , ‘cannot fulfill request.’ ) ,


When an error is raised the server responds by returning an HTTP error

multinational debit card owned by mastercard

Code and an error page. You can use the httperror instance as a

Response on the page returned. This means that as well as the code

Attribute, it also has read, geturl, and info, methods.

>>> req = urllib2.Request(‘http://www.Python.Org/fish.Html’)

>>> try:

>>> urllib2.Urlopen(req)

>>> except urlerror, e:

>>> print e.Code

>>> print e.Read()



Error 404: file not found

…… Etc…

Openers and handlers

When you fetch a URL you use an opener (an instance of the perhaps

Confusingly-named urllib2.OpenerDirector). Normally we have been using

The default opener – via urlopen – but you can create custom

Openers. Openers use handlers. All the heavy lifting is done by the

Handlers. Each handler knows how to open urls for a particular URL

multinational debit card owned by mastercard

Scheme (http, ftp, etc.), or how to handle an aspect of URL opening,

For example HTTP redirections or HTTP cookies.

You will want to create openers if you want to fetch urls with

Specific handlers installed, for example to get an opener that handles

Cookies, or to get an opener that does not handle redirections.

To create an opener, instantiate an openerdirector, and then call

.Add handler(some handler instance) repeatedly.

Alternatively, you can use build opener, which is a convenience

Function for creating opener objects with a single function call.

Build opener adds several handlers by default, but provides a

Quick way to add more and/or override the default handlers.

Other sorts of handlers you might want to can handle proxies,

Authentication, and other common but slightly specialised

multinational debit card owned by mastercard


Install opener can be used to make an opener object the

(global) default opener. This means that calls to urlopen will use

The opener you have installed.

Opener objects have an open method, which can be called directly

To fetch urls in the same way as the urlopen function: there’s no

Need to call install opener, except as a convenience.

Basic authentication

To illustrate creating and installing a handler we will use the

HTTPBasicAuthHandler. For a more detailed discussion of this

Subject – including an explanation of how basic authentication works –

See the basic authentication tutorial.

When authentication is required, the server sends a header (as well as

The 401 error code) requesting authentication. This specifies the

Authentication scheme and a ‘realm’.Multinational debit card owned by mastercard the header looks like :

Www-authenticate: SCHEME realm=REALM.


Www-authenticate: basic realm=cpanel users

The client should then retry the request with the appropriate name and

Password for the realm included as a header in the request. This is

‘basic authentication’. In order to simplify this process we can

Create an instance of httpbasicauthhandler and an opener to use

This handler.

The httpbasicauthhandler uses an object called a password manager

To handle the mapping of urls and realms to passwords and

Usernames. If you know what the realm is (from the authentication

Header sent by the server), then you can use a

HTTPPasswordMgr. Frequently one doesn’t care what the realm is. In

That case, it is convenient to use

HTTPPasswordMgrWithDefaultRealm. This allows you to specify a

multinational debit card owned by mastercard

Default username and password for a URL. This will be supplied in the

Absence of you providing an alternative combination for a specific

Realm. We indicate this by providing none as the realm argument to

The add password method.

The top-level URL is the first URL that requires authentication. URLs

Deeper than the URL you pass to .Add password() will also match.