blob: 058cf967ecd0a4494db53fe2cdedc7f468ca81b2 [file] [log] [blame]
Georg Brandl9e4ff752009-12-19 17:57:51 +00001.. _urllib-howto:
2
Georg Brandl0f7ede42008-06-23 11:23:31 +00003***********************************************************
4 HOWTO Fetch Internet Resources Using The urllib Package
5***********************************************************
Georg Brandl116aa622007-08-15 14:28:22 +00006
7:Author: `Michael Foord <http://www.voidspace.org.uk/python/index.shtml>`_
8
9.. note::
10
Georg Brandl0f7ede42008-06-23 11:23:31 +000011 There is a French translation of an earlier revision of this
Georg Brandl116aa622007-08-15 14:28:22 +000012 HOWTO, available at `urllib2 - Le Manuel manquant
Christian Heimesdd15f6c2008-03-16 00:07:10 +000013 <http://www.voidspace.org.uk/python/articles/urllib2_francais.shtml>`_.
Georg Brandl116aa622007-08-15 14:28:22 +000014
Georg Brandl48310cd2009-01-03 21:18:54 +000015
Georg Brandl116aa622007-08-15 14:28:22 +000016
17Introduction
18============
19
20.. sidebar:: Related Articles
21
22 You may also find useful the following article on fetching web resources
Georg Brandl0f7ede42008-06-23 11:23:31 +000023 with Python:
Georg Brandl48310cd2009-01-03 21:18:54 +000024
Georg Brandl116aa622007-08-15 14:28:22 +000025 * `Basic Authentication <http://www.voidspace.org.uk/python/articles/authentication.shtml>`_
Georg Brandl48310cd2009-01-03 21:18:54 +000026
Georg Brandl116aa622007-08-15 14:28:22 +000027 A tutorial on *Basic Authentication*, with examples in Python.
28
Senthil Kumaranaca8fd72008-06-23 04:41:59 +000029**urllib.request** is a `Python <http://www.python.org>`_ module for fetching URLs
Georg Brandl116aa622007-08-15 14:28:22 +000030(Uniform Resource Locators). It offers a very simple interface, in the form of
31the *urlopen* function. This is capable of fetching URLs using a variety of
32different protocols. It also offers a slightly more complex interface for
33handling common situations - like basic authentication, cookies, proxies and so
34on. These are provided by objects called handlers and openers.
35
Senthil Kumaranaca8fd72008-06-23 04:41:59 +000036urllib.request supports fetching URLs for many "URL schemes" (identified by the string
Georg Brandl116aa622007-08-15 14:28:22 +000037before the ":" in URL - for example "ftp" is the URL scheme of
38"ftp://python.org/") using their associated network protocols (e.g. FTP, HTTP).
39This tutorial focuses on the most common case, HTTP.
40
41For straightforward situations *urlopen* is very easy to use. But as soon as you
42encounter errors or non-trivial cases when opening HTTP URLs, you will need some
43understanding of the HyperText Transfer Protocol. The most comprehensive and
44authoritative reference to HTTP is :rfc:`2616`. This is a technical document and
Senthil Kumaranaca8fd72008-06-23 04:41:59 +000045not intended to be easy to read. This HOWTO aims to illustrate using *urllib*,
Georg Brandl116aa622007-08-15 14:28:22 +000046with enough detail about HTTP to help you through. It is not intended to replace
Senthil Kumaranaca8fd72008-06-23 04:41:59 +000047the :mod:`urllib.request` docs, but is supplementary to them.
Georg Brandl116aa622007-08-15 14:28:22 +000048
49
50Fetching URLs
51=============
52
Senthil Kumaranaca8fd72008-06-23 04:41:59 +000053The simplest way to use urllib.request is as follows::
Georg Brandl116aa622007-08-15 14:28:22 +000054
Senthil Kumaranaca8fd72008-06-23 04:41:59 +000055 import urllib.request
56 response = urllib.request.urlopen('http://python.org/')
Georg Brandl116aa622007-08-15 14:28:22 +000057 html = response.read()
58
Senthil Kumarane24f96a2012-03-13 19:29:33 -070059If you wish to retrieve a resource via URL and store it in a temporary location,
60you can do so via the :func:`urlretrieve` function::
61
62 import urllib.request
63 local_filename, headers = urllib.request.urlretrieve('http://python.org/')
64 html = open(local_filename)
65
Senthil Kumaranaca8fd72008-06-23 04:41:59 +000066Many uses of urllib will be that simple (note that instead of an 'http:' URL we
Georg Brandl116aa622007-08-15 14:28:22 +000067could have used an URL starting with 'ftp:', 'file:', etc.). However, it's the
68purpose of this tutorial to explain the more complicated cases, concentrating on
69HTTP.
70
71HTTP is based on requests and responses - the client makes requests and servers
Senthil Kumaranaca8fd72008-06-23 04:41:59 +000072send responses. urllib.request mirrors this with a ``Request`` object which represents
Georg Brandl116aa622007-08-15 14:28:22 +000073the HTTP request you are making. In its simplest form you create a Request
74object that specifies the URL you want to fetch. Calling ``urlopen`` with this
75Request object returns a response object for the URL requested. This response is
76a file-like object, which means you can for example call ``.read()`` on the
77response::
78
Senthil Kumaranaca8fd72008-06-23 04:41:59 +000079 import urllib.request
Georg Brandl116aa622007-08-15 14:28:22 +000080
Senthil Kumaranaca8fd72008-06-23 04:41:59 +000081 req = urllib.request.Request('http://www.voidspace.org.uk')
82 response = urllib.request.urlopen(req)
Georg Brandl116aa622007-08-15 14:28:22 +000083 the_page = response.read()
84
Senthil Kumaranaca8fd72008-06-23 04:41:59 +000085Note that urllib.request makes use of the same Request interface to handle all URL
Georg Brandl116aa622007-08-15 14:28:22 +000086schemes. For example, you can make an FTP request like so::
87
Senthil Kumaranaca8fd72008-06-23 04:41:59 +000088 req = urllib.request.Request('ftp://example.com/')
Georg Brandl116aa622007-08-15 14:28:22 +000089
90In the case of HTTP, there are two extra things that Request objects allow you
91to do: First, you can pass data to be sent to the server. Second, you can pass
92extra information ("metadata") *about* the data or the about request itself, to
93the server - this information is sent as HTTP "headers". Let's look at each of
94these in turn.
95
96Data
97----
98
99Sometimes you want to send data to a URL (often the URL will refer to a CGI
100(Common Gateway Interface) script [#]_ or other web application). With HTTP,
101this is often done using what's known as a **POST** request. This is often what
102your browser does when you submit a HTML form that you filled in on the web. Not
103all POSTs have to come from forms: you can use a POST to transmit arbitrary data
104to your own application. In the common case of HTML forms, the data needs to be
105encoded in a standard way, and then passed to the Request object as the ``data``
Georg Brandl0f7ede42008-06-23 11:23:31 +0000106argument. The encoding is done using a function from the :mod:`urllib.parse`
107library. ::
Georg Brandl116aa622007-08-15 14:28:22 +0000108
Senthil Kumaranaca8fd72008-06-23 04:41:59 +0000109 import urllib.parse
Georg Brandl48310cd2009-01-03 21:18:54 +0000110 import urllib.request
Georg Brandl116aa622007-08-15 14:28:22 +0000111
112 url = 'http://www.someserver.com/cgi-bin/register.cgi'
113 values = {'name' : 'Michael Foord',
114 'location' : 'Northampton',
115 'language' : 'Python' }
116
Senthil Kumaranaca8fd72008-06-23 04:41:59 +0000117 data = urllib.parse.urlencode(values)
118 req = urllib.request.Request(url, data)
119 response = urllib.request.urlopen(req)
Georg Brandl116aa622007-08-15 14:28:22 +0000120 the_page = response.read()
121
122Note that other encodings are sometimes required (e.g. for file upload from HTML
123forms - see `HTML Specification, Form Submission
124<http://www.w3.org/TR/REC-html40/interact/forms.html#h-17.13>`_ for more
125details).
126
Georg Brandl0f7ede42008-06-23 11:23:31 +0000127If you do not pass the ``data`` argument, urllib uses a **GET** request. One
Georg Brandl116aa622007-08-15 14:28:22 +0000128way in which GET and POST requests differ is that POST requests often have
129"side-effects": they change the state of the system in some way (for example by
130placing an order with the website for a hundredweight of tinned spam to be
131delivered to your door). Though the HTTP standard makes it clear that POSTs are
132intended to *always* cause side-effects, and GET requests *never* to cause
133side-effects, nothing prevents a GET request from having side-effects, nor a
134POST requests from having no side-effects. Data can also be passed in an HTTP
135GET request by encoding it in the URL itself.
136
137This is done as follows::
138
Senthil Kumaranaca8fd72008-06-23 04:41:59 +0000139 >>> import urllib.request
140 >>> import urllib.parse
Georg Brandl116aa622007-08-15 14:28:22 +0000141 >>> data = {}
142 >>> data['name'] = 'Somebody Here'
143 >>> data['location'] = 'Northampton'
144 >>> data['language'] = 'Python'
Senthil Kumaranaca8fd72008-06-23 04:41:59 +0000145 >>> url_values = urllib.parse.urlencode(data)
Georg Brandl6911e3c2007-09-04 07:15:32 +0000146 >>> print(url_values)
Georg Brandl116aa622007-08-15 14:28:22 +0000147 name=Somebody+Here&language=Python&location=Northampton
148 >>> url = 'http://www.example.com/example.cgi'
149 >>> full_url = url + '?' + url_values
Georg Brandl06ad13e2011-07-23 08:04:40 +0200150 >>> data = urllib.request.urlopen(full_url)
Georg Brandl116aa622007-08-15 14:28:22 +0000151
152Notice that the full URL is created by adding a ``?`` to the URL, followed by
153the encoded values.
154
155Headers
156-------
157
158We'll discuss here one particular HTTP header, to illustrate how to add headers
159to your HTTP request.
160
161Some websites [#]_ dislike being browsed by programs, or send different versions
Senthil Kumaranaca8fd72008-06-23 04:41:59 +0000162to different browsers [#]_ . By default urllib identifies itself as
Georg Brandl116aa622007-08-15 14:28:22 +0000163``Python-urllib/x.y`` (where ``x`` and ``y`` are the major and minor version
164numbers of the Python release,
165e.g. ``Python-urllib/2.5``), which may confuse the site, or just plain
166not work. The way a browser identifies itself is through the
167``User-Agent`` header [#]_. When you create a Request object you can
168pass a dictionary of headers in. The following example makes the same
169request as above, but identifies itself as a version of Internet
170Explorer [#]_. ::
171
Senthil Kumaranaca8fd72008-06-23 04:41:59 +0000172 import urllib.parse
Georg Brandl48310cd2009-01-03 21:18:54 +0000173 import urllib.request
174
Georg Brandl116aa622007-08-15 14:28:22 +0000175 url = 'http://www.someserver.com/cgi-bin/register.cgi'
Georg Brandl48310cd2009-01-03 21:18:54 +0000176 user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
Georg Brandl116aa622007-08-15 14:28:22 +0000177 values = {'name' : 'Michael Foord',
178 'location' : 'Northampton',
179 'language' : 'Python' }
180 headers = { 'User-Agent' : user_agent }
Georg Brandl48310cd2009-01-03 21:18:54 +0000181
Senthil Kumaranaca8fd72008-06-23 04:41:59 +0000182 data = urllib.parse.urlencode(values)
183 req = urllib.request.Request(url, data, headers)
184 response = urllib.request.urlopen(req)
Georg Brandl116aa622007-08-15 14:28:22 +0000185 the_page = response.read()
186
187The response also has two useful methods. See the section on `info and geturl`_
188which comes after we have a look at what happens when things go wrong.
189
190
191Handling Exceptions
192===================
193
Georg Brandl22b34312009-07-26 14:54:51 +0000194*urlopen* raises :exc:`URLError` when it cannot handle a response (though as
195usual with Python APIs, built-in exceptions such as :exc:`ValueError`,
196:exc:`TypeError` etc. may also be raised).
Georg Brandl116aa622007-08-15 14:28:22 +0000197
Benjamin Petersone5384b02008-10-04 22:00:42 +0000198:exc:`HTTPError` is the subclass of :exc:`URLError` raised in the specific case of
Georg Brandl116aa622007-08-15 14:28:22 +0000199HTTP URLs.
200
Georg Brandl0f7ede42008-06-23 11:23:31 +0000201The exception classes are exported from the :mod:`urllib.error` module.
202
Georg Brandl116aa622007-08-15 14:28:22 +0000203URLError
204--------
205
206Often, URLError is raised because there is no network connection (no route to
207the specified server), or the specified server doesn't exist. In this case, the
208exception raised will have a 'reason' attribute, which is a tuple containing an
209error code and a text error message.
210
211e.g. ::
212
Senthil Kumaranaca8fd72008-06-23 04:41:59 +0000213 >>> req = urllib.request.Request('http://www.pretend_server.org')
214 >>> try: urllib.request.urlopen(req)
Michael Foord20b50b12009-05-12 11:19:14 +0000215 >>> except urllib.error.URLError as e:
Georg Brandl6911e3c2007-09-04 07:15:32 +0000216 >>> print(e.reason)
Georg Brandl116aa622007-08-15 14:28:22 +0000217 >>>
218 (4, 'getaddrinfo failed')
219
220
221HTTPError
222---------
223
224Every HTTP response from the server contains a numeric "status code". Sometimes
225the status code indicates that the server is unable to fulfil the request. The
226default handlers will handle some of these responses for you (for example, if
227the response is a "redirection" that requests the client fetch the document from
Georg Brandl0f7ede42008-06-23 11:23:31 +0000228a different URL, urllib will handle that for you). For those it can't handle,
Benjamin Petersone5384b02008-10-04 22:00:42 +0000229urlopen will raise an :exc:`HTTPError`. Typical errors include '404' (page not
Georg Brandl116aa622007-08-15 14:28:22 +0000230found), '403' (request forbidden), and '401' (authentication required).
231
232See section 10 of RFC 2616 for a reference on all the HTTP error codes.
233
Benjamin Petersone5384b02008-10-04 22:00:42 +0000234The :exc:`HTTPError` instance raised will have an integer 'code' attribute, which
Georg Brandl116aa622007-08-15 14:28:22 +0000235corresponds to the error sent by the server.
236
237Error Codes
238~~~~~~~~~~~
239
240Because the default handlers handle redirects (codes in the 300 range), and
241codes in the 100-299 range indicate success, you will usually only see error
242codes in the 400-599 range.
243
Georg Brandl24420152008-05-26 16:32:26 +0000244:attr:`http.server.BaseHTTPRequestHandler.responses` is a useful dictionary of
Georg Brandl116aa622007-08-15 14:28:22 +0000245response codes in that shows all the response codes used by RFC 2616. The
246dictionary is reproduced here for convenience ::
247
248 # Table mapping response codes to messages; entries have the
249 # form {code: (shortmessage, longmessage)}.
250 responses = {
251 100: ('Continue', 'Request received, please continue'),
252 101: ('Switching Protocols',
253 'Switching to new protocol; obey Upgrade header'),
254
255 200: ('OK', 'Request fulfilled, document follows'),
256 201: ('Created', 'Document created, URL follows'),
257 202: ('Accepted',
258 'Request accepted, processing continues off-line'),
259 203: ('Non-Authoritative Information', 'Request fulfilled from cache'),
260 204: ('No Content', 'Request fulfilled, nothing follows'),
261 205: ('Reset Content', 'Clear input form for further input.'),
262 206: ('Partial Content', 'Partial content follows.'),
263
264 300: ('Multiple Choices',
265 'Object has several resources -- see URI list'),
266 301: ('Moved Permanently', 'Object moved permanently -- see URI list'),
267 302: ('Found', 'Object moved temporarily -- see URI list'),
268 303: ('See Other', 'Object moved -- see Method and URL list'),
269 304: ('Not Modified',
270 'Document has not changed since given time'),
271 305: ('Use Proxy',
272 'You must use proxy specified in Location to access this '
273 'resource.'),
274 307: ('Temporary Redirect',
275 'Object moved temporarily -- see URI list'),
276
277 400: ('Bad Request',
278 'Bad request syntax or unsupported method'),
279 401: ('Unauthorized',
280 'No permission -- see authorization schemes'),
281 402: ('Payment Required',
282 'No payment -- see charging schemes'),
283 403: ('Forbidden',
284 'Request forbidden -- authorization will not help'),
285 404: ('Not Found', 'Nothing matches the given URI'),
286 405: ('Method Not Allowed',
287 'Specified method is invalid for this server.'),
288 406: ('Not Acceptable', 'URI not available in preferred format.'),
289 407: ('Proxy Authentication Required', 'You must authenticate with '
290 'this proxy before proceeding.'),
291 408: ('Request Timeout', 'Request timed out; try again later.'),
292 409: ('Conflict', 'Request conflict.'),
293 410: ('Gone',
294 'URI no longer exists and has been permanently removed.'),
295 411: ('Length Required', 'Client must specify Content-Length.'),
296 412: ('Precondition Failed', 'Precondition in headers is false.'),
297 413: ('Request Entity Too Large', 'Entity is too large.'),
298 414: ('Request-URI Too Long', 'URI is too long.'),
299 415: ('Unsupported Media Type', 'Entity body in unsupported format.'),
300 416: ('Requested Range Not Satisfiable',
301 'Cannot satisfy request range.'),
302 417: ('Expectation Failed',
303 'Expect condition could not be satisfied.'),
304
305 500: ('Internal Server Error', 'Server got itself in trouble'),
306 501: ('Not Implemented',
307 'Server does not support this operation'),
308 502: ('Bad Gateway', 'Invalid responses from another server/proxy.'),
309 503: ('Service Unavailable',
310 'The server cannot process the request due to a high load'),
311 504: ('Gateway Timeout',
312 'The gateway server did not receive a timely response'),
313 505: ('HTTP Version Not Supported', 'Cannot fulfill request.'),
314 }
315
316When an error is raised the server responds by returning an HTTP error code
Benjamin Petersone5384b02008-10-04 22:00:42 +0000317*and* an error page. You can use the :exc:`HTTPError` instance as a response on the
Georg Brandl116aa622007-08-15 14:28:22 +0000318page returned. This means that as well as the code attribute, it also has read,
Senthil Kumaranaca8fd72008-06-23 04:41:59 +0000319geturl, and info, methods as returned by the ``urllib.response`` module::
Georg Brandl116aa622007-08-15 14:28:22 +0000320
Senthil Kumaranaca8fd72008-06-23 04:41:59 +0000321 >>> req = urllib.request.Request('http://www.python.org/fish.html')
Georg Brandl48310cd2009-01-03 21:18:54 +0000322 >>> try:
Senthil Kumaranaca8fd72008-06-23 04:41:59 +0000323 >>> urllib.request.urlopen(req)
Georg Brandlfe5f4092009-05-22 10:44:31 +0000324 >>> except urllib.error.HTTPError as e:
Georg Brandl6911e3c2007-09-04 07:15:32 +0000325 >>> print(e.code)
326 >>> print(e.read())
Georg Brandl48310cd2009-01-03 21:18:54 +0000327 >>>
Georg Brandl116aa622007-08-15 14:28:22 +0000328 404
Georg Brandl48310cd2009-01-03 21:18:54 +0000329 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
Georg Brandl116aa622007-08-15 14:28:22 +0000330 "http://www.w3.org/TR/html4/loose.dtd">
Georg Brandl48310cd2009-01-03 21:18:54 +0000331 <?xml-stylesheet href="./css/ht2html.css"
Georg Brandl116aa622007-08-15 14:28:22 +0000332 type="text/css"?>
Georg Brandl48310cd2009-01-03 21:18:54 +0000333 <html><head><title>Error 404: File Not Found</title>
Georg Brandl116aa622007-08-15 14:28:22 +0000334 ...... etc...
335
336Wrapping it Up
337--------------
338
Benjamin Petersone5384b02008-10-04 22:00:42 +0000339So if you want to be prepared for :exc:`HTTPError` *or* :exc:`URLError` there are two
Georg Brandl116aa622007-08-15 14:28:22 +0000340basic approaches. I prefer the second approach.
341
342Number 1
343~~~~~~~~
344
345::
346
347
Senthil Kumaranaca8fd72008-06-23 04:41:59 +0000348 from urllib.request import Request, urlopen
349 from urllib.error import URLError, HTTPError
Georg Brandl116aa622007-08-15 14:28:22 +0000350 req = Request(someurl)
351 try:
352 response = urlopen(req)
Michael Foord20b50b12009-05-12 11:19:14 +0000353 except HTTPError as e:
Georg Brandl6911e3c2007-09-04 07:15:32 +0000354 print('The server couldn\'t fulfill the request.')
355 print('Error code: ', e.code)
Michael Foord20b50b12009-05-12 11:19:14 +0000356 except URLError as e:
Georg Brandl6911e3c2007-09-04 07:15:32 +0000357 print('We failed to reach a server.')
358 print('Reason: ', e.reason)
Georg Brandl116aa622007-08-15 14:28:22 +0000359 else:
360 # everything is fine
361
362
363.. note::
364
365 The ``except HTTPError`` *must* come first, otherwise ``except URLError``
Benjamin Petersone5384b02008-10-04 22:00:42 +0000366 will *also* catch an :exc:`HTTPError`.
Georg Brandl116aa622007-08-15 14:28:22 +0000367
368Number 2
369~~~~~~~~
370
371::
372
Senthil Kumaranaca8fd72008-06-23 04:41:59 +0000373 from urllib.request import Request, urlopen
374 from urllib.error import URLError
Georg Brandl116aa622007-08-15 14:28:22 +0000375 req = Request(someurl)
376 try:
377 response = urlopen(req)
Michael Foord20b50b12009-05-12 11:19:14 +0000378 except URLError as e:
Georg Brandl116aa622007-08-15 14:28:22 +0000379 if hasattr(e, 'reason'):
Georg Brandl6911e3c2007-09-04 07:15:32 +0000380 print('We failed to reach a server.')
381 print('Reason: ', e.reason)
Georg Brandl116aa622007-08-15 14:28:22 +0000382 elif hasattr(e, 'code'):
Georg Brandl6911e3c2007-09-04 07:15:32 +0000383 print('The server couldn\'t fulfill the request.')
384 print('Error code: ', e.code)
Georg Brandl116aa622007-08-15 14:28:22 +0000385 else:
386 # everything is fine
Georg Brandl48310cd2009-01-03 21:18:54 +0000387
Georg Brandl116aa622007-08-15 14:28:22 +0000388
389info and geturl
390===============
391
Benjamin Petersone5384b02008-10-04 22:00:42 +0000392The response returned by urlopen (or the :exc:`HTTPError` instance) has two
393useful methods :meth:`info` and :meth:`geturl` and is defined in the module
394:mod:`urllib.response`..
Georg Brandl116aa622007-08-15 14:28:22 +0000395
396**geturl** - this returns the real URL of the page fetched. This is useful
397because ``urlopen`` (or the opener object used) may have followed a
398redirect. The URL of the page fetched may not be the same as the URL requested.
399
400**info** - this returns a dictionary-like object that describes the page
401fetched, particularly the headers sent by the server. It is currently an
Georg Brandl0f7ede42008-06-23 11:23:31 +0000402:class:`http.client.HTTPMessage` instance.
Georg Brandl116aa622007-08-15 14:28:22 +0000403
404Typical headers include 'Content-length', 'Content-type', and so on. See the
405`Quick Reference to HTTP Headers <http://www.cs.tut.fi/~jkorpela/http.html>`_
406for a useful listing of HTTP headers with brief explanations of their meaning
407and use.
408
409
410Openers and Handlers
411====================
412
413When you fetch a URL you use an opener (an instance of the perhaps
Senthil Kumaranaca8fd72008-06-23 04:41:59 +0000414confusingly-named :class:`urllib.request.OpenerDirector`). Normally we have been using
Georg Brandl116aa622007-08-15 14:28:22 +0000415the default opener - via ``urlopen`` - but you can create custom
416openers. Openers use handlers. All the "heavy lifting" is done by the
417handlers. Each handler knows how to open URLs for a particular URL scheme (http,
418ftp, etc.), or how to handle an aspect of URL opening, for example HTTP
419redirections or HTTP cookies.
420
421You will want to create openers if you want to fetch URLs with specific handlers
422installed, for example to get an opener that handles cookies, or to get an
423opener that does not handle redirections.
424
425To create an opener, instantiate an ``OpenerDirector``, and then call
426``.add_handler(some_handler_instance)`` repeatedly.
427
428Alternatively, you can use ``build_opener``, which is a convenience function for
429creating opener objects with a single function call. ``build_opener`` adds
430several handlers by default, but provides a quick way to add more and/or
431override the default handlers.
432
433Other sorts of handlers you might want to can handle proxies, authentication,
434and other common but slightly specialised situations.
435
436``install_opener`` can be used to make an ``opener`` object the (global) default
437opener. This means that calls to ``urlopen`` will use the opener you have
438installed.
439
440Opener objects have an ``open`` method, which can be called directly to fetch
441urls in the same way as the ``urlopen`` function: there's no need to call
442``install_opener``, except as a convenience.
443
444
445Basic Authentication
446====================
447
448To illustrate creating and installing a handler we will use the
449``HTTPBasicAuthHandler``. For a more detailed discussion of this subject --
450including an explanation of how Basic Authentication works - see the `Basic
451Authentication Tutorial
452<http://www.voidspace.org.uk/python/articles/authentication.shtml>`_.
453
454When authentication is required, the server sends a header (as well as the 401
455error code) requesting authentication. This specifies the authentication scheme
456and a 'realm'. The header looks like : ``Www-authenticate: SCHEME
457realm="REALM"``.
458
Georg Brandl48310cd2009-01-03 21:18:54 +0000459e.g. ::
Georg Brandl116aa622007-08-15 14:28:22 +0000460
461 Www-authenticate: Basic realm="cPanel Users"
462
463
464The client should then retry the request with the appropriate name and password
465for the realm included as a header in the request. This is 'basic
466authentication'. In order to simplify this process we can create an instance of
467``HTTPBasicAuthHandler`` and an opener to use this handler.
468
469The ``HTTPBasicAuthHandler`` uses an object called a password manager to handle
470the mapping of URLs and realms to passwords and usernames. If you know what the
471realm is (from the authentication header sent by the server), then you can use a
472``HTTPPasswordMgr``. Frequently one doesn't care what the realm is. In that
473case, it is convenient to use ``HTTPPasswordMgrWithDefaultRealm``. This allows
474you to specify a default username and password for a URL. This will be supplied
475in the absence of you providing an alternative combination for a specific
476realm. We indicate this by providing ``None`` as the realm argument to the
477``add_password`` method.
478
479The top-level URL is the first URL that requires authentication. URLs "deeper"
480than the URL you pass to .add_password() will also match. ::
481
482 # create a password manager
Georg Brandl48310cd2009-01-03 21:18:54 +0000483 password_mgr = urllib.request.HTTPPasswordMgrWithDefaultRealm()
Georg Brandl116aa622007-08-15 14:28:22 +0000484
485 # Add the username and password.
Georg Brandl1f01deb2009-01-03 22:47:39 +0000486 # If we knew the realm, we could use it instead of None.
Georg Brandl116aa622007-08-15 14:28:22 +0000487 top_level_url = "http://example.com/foo/"
488 password_mgr.add_password(None, top_level_url, username, password)
489
Georg Brandl48310cd2009-01-03 21:18:54 +0000490 handler = urllib.request.HTTPBasicAuthHandler(password_mgr)
Georg Brandl116aa622007-08-15 14:28:22 +0000491
492 # create "opener" (OpenerDirector instance)
Georg Brandl48310cd2009-01-03 21:18:54 +0000493 opener = urllib.request.build_opener(handler)
Georg Brandl116aa622007-08-15 14:28:22 +0000494
495 # use the opener to fetch a URL
Georg Brandl48310cd2009-01-03 21:18:54 +0000496 opener.open(a_url)
Georg Brandl116aa622007-08-15 14:28:22 +0000497
498 # Install the opener.
Senthil Kumaranaca8fd72008-06-23 04:41:59 +0000499 # Now all calls to urllib.request.urlopen use our opener.
Georg Brandl48310cd2009-01-03 21:18:54 +0000500 urllib.request.install_opener(opener)
Georg Brandl116aa622007-08-15 14:28:22 +0000501
502.. note::
503
Ezio Melotti8e87fec2009-07-21 20:37:52 +0000504 In the above example we only supplied our ``HTTPBasicAuthHandler`` to
Georg Brandl116aa622007-08-15 14:28:22 +0000505 ``build_opener``. By default openers have the handlers for normal situations
506 -- ``ProxyHandler``, ``UnknownHandler``, ``HTTPHandler``,
507 ``HTTPDefaultErrorHandler``, ``HTTPRedirectHandler``, ``FTPHandler``,
508 ``FileHandler``, ``HTTPErrorProcessor``.
509
510``top_level_url`` is in fact *either* a full URL (including the 'http:' scheme
511component and the hostname and optionally the port number)
512e.g. "http://example.com/" *or* an "authority" (i.e. the hostname,
513optionally including the port number) e.g. "example.com" or "example.com:8080"
514(the latter example includes a port number). The authority, if present, must
515NOT contain the "userinfo" component - for example "joe@password:example.com" is
516not correct.
517
518
519Proxies
520=======
521
Georg Brandl0f7ede42008-06-23 11:23:31 +0000522**urllib** will auto-detect your proxy settings and use those. This is through
Georg Brandl116aa622007-08-15 14:28:22 +0000523the ``ProxyHandler`` which is part of the normal handler chain. Normally that's
524a good thing, but there are occasions when it may not be helpful [#]_. One way
525to do this is to setup our own ``ProxyHandler``, with no proxies defined. This
526is done using similar steps to setting up a `Basic Authentication`_ handler : ::
527
Senthil Kumaranaca8fd72008-06-23 04:41:59 +0000528 >>> proxy_support = urllib.request.ProxyHandler({})
529 >>> opener = urllib.request.build_opener(proxy_support)
530 >>> urllib.request.install_opener(opener)
Georg Brandl116aa622007-08-15 14:28:22 +0000531
532.. note::
533
Senthil Kumaranaca8fd72008-06-23 04:41:59 +0000534 Currently ``urllib.request`` *does not* support fetching of ``https`` locations
535 through a proxy. However, this can be enabled by extending urllib.request as
Georg Brandl116aa622007-08-15 14:28:22 +0000536 shown in the recipe [#]_.
537
538
539Sockets and Layers
540==================
541
Georg Brandl0f7ede42008-06-23 11:23:31 +0000542The Python support for fetching resources from the web is layered. urllib uses
543the :mod:`http.client` library, which in turn uses the socket library.
Georg Brandl116aa622007-08-15 14:28:22 +0000544
545As of Python 2.3 you can specify how long a socket should wait for a response
546before timing out. This can be useful in applications which have to fetch web
547pages. By default the socket module has *no timeout* and can hang. Currently,
Senthil Kumaranaca8fd72008-06-23 04:41:59 +0000548the socket timeout is not exposed at the http.client or urllib.request levels.
Georg Brandl24420152008-05-26 16:32:26 +0000549However, you can set the default timeout globally for all sockets using ::
Georg Brandl116aa622007-08-15 14:28:22 +0000550
551 import socket
Senthil Kumaranaca8fd72008-06-23 04:41:59 +0000552 import urllib.request
Georg Brandl116aa622007-08-15 14:28:22 +0000553
554 # timeout in seconds
555 timeout = 10
Georg Brandl48310cd2009-01-03 21:18:54 +0000556 socket.setdefaulttimeout(timeout)
Georg Brandl116aa622007-08-15 14:28:22 +0000557
Senthil Kumaranaca8fd72008-06-23 04:41:59 +0000558 # this call to urllib.request.urlopen now uses the default timeout
Georg Brandl116aa622007-08-15 14:28:22 +0000559 # we have set in the socket module
Senthil Kumaranaca8fd72008-06-23 04:41:59 +0000560 req = urllib.request.Request('http://www.voidspace.org.uk')
561 response = urllib.request.urlopen(req)
Georg Brandl116aa622007-08-15 14:28:22 +0000562
563
564-------
565
566
567Footnotes
568=========
569
570This document was reviewed and revised by John Lee.
571
572.. [#] For an introduction to the CGI protocol see
Georg Brandl48310cd2009-01-03 21:18:54 +0000573 `Writing Web Applications in Python <http://www.pyzine.com/Issue008/Section_Articles/article_CGIOne.html>`_.
Georg Brandl116aa622007-08-15 14:28:22 +0000574.. [#] Like Google for example. The *proper* way to use google from a program
575 is to use `PyGoogle <http://pygoogle.sourceforge.net>`_ of course. See
576 `Voidspace Google <http://www.voidspace.org.uk/python/recipebook.shtml#google>`_
577 for some examples of using the Google API.
578.. [#] Browser sniffing is a very bad practise for website design - building
579 sites using web standards is much more sensible. Unfortunately a lot of
580 sites still send different versions to different browsers.
581.. [#] The user agent for MSIE 6 is
582 *'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322)'*
583.. [#] For details of more HTTP request headers, see
584 `Quick Reference to HTTP Headers`_.
585.. [#] In my case I have to use a proxy to access the internet at work. If you
586 attempt to fetch *localhost* URLs through this proxy it blocks them. IE
Georg Brandl0f7ede42008-06-23 11:23:31 +0000587 is set to use the proxy, which urllib picks up on. In order to test
588 scripts with a localhost server, I have to prevent urllib from using
Georg Brandl116aa622007-08-15 14:28:22 +0000589 the proxy.
Georg Brandl48310cd2009-01-03 21:18:54 +0000590.. [#] urllib opener for SSL proxy (CONNECT method): `ASPN Cookbook Recipe
Georg Brandl116aa622007-08-15 14:28:22 +0000591 <http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/456195>`_.
Georg Brandl48310cd2009-01-03 21:18:54 +0000592