blob: 567c1b1820498d6c832b4e8615ccf4c03ac741df [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 Kumaranaca8fd72008-06-23 04:41:59 +000059Many uses of urllib will be that simple (note that instead of an 'http:' URL we
Georg Brandl116aa622007-08-15 14:28:22 +000060could have used an URL starting with 'ftp:', 'file:', etc.). However, it's the
61purpose of this tutorial to explain the more complicated cases, concentrating on
62HTTP.
63
64HTTP is based on requests and responses - the client makes requests and servers
Senthil Kumaranaca8fd72008-06-23 04:41:59 +000065send responses. urllib.request mirrors this with a ``Request`` object which represents
Georg Brandl116aa622007-08-15 14:28:22 +000066the HTTP request you are making. In its simplest form you create a Request
67object that specifies the URL you want to fetch. Calling ``urlopen`` with this
68Request object returns a response object for the URL requested. This response is
69a file-like object, which means you can for example call ``.read()`` on the
70response::
71
Senthil Kumaranaca8fd72008-06-23 04:41:59 +000072 import urllib.request
Georg Brandl116aa622007-08-15 14:28:22 +000073
Senthil Kumaranaca8fd72008-06-23 04:41:59 +000074 req = urllib.request.Request('http://www.voidspace.org.uk')
75 response = urllib.request.urlopen(req)
Georg Brandl116aa622007-08-15 14:28:22 +000076 the_page = response.read()
77
Senthil Kumaranaca8fd72008-06-23 04:41:59 +000078Note that urllib.request makes use of the same Request interface to handle all URL
Georg Brandl116aa622007-08-15 14:28:22 +000079schemes. For example, you can make an FTP request like so::
80
Senthil Kumaranaca8fd72008-06-23 04:41:59 +000081 req = urllib.request.Request('ftp://example.com/')
Georg Brandl116aa622007-08-15 14:28:22 +000082
83In the case of HTTP, there are two extra things that Request objects allow you
84to do: First, you can pass data to be sent to the server. Second, you can pass
85extra information ("metadata") *about* the data or the about request itself, to
86the server - this information is sent as HTTP "headers". Let's look at each of
87these in turn.
88
89Data
90----
91
92Sometimes you want to send data to a URL (often the URL will refer to a CGI
93(Common Gateway Interface) script [#]_ or other web application). With HTTP,
94this is often done using what's known as a **POST** request. This is often what
95your browser does when you submit a HTML form that you filled in on the web. Not
96all POSTs have to come from forms: you can use a POST to transmit arbitrary data
97to your own application. In the common case of HTML forms, the data needs to be
98encoded in a standard way, and then passed to the Request object as the ``data``
Georg Brandl0f7ede42008-06-23 11:23:31 +000099argument. The encoding is done using a function from the :mod:`urllib.parse`
100library. ::
Georg Brandl116aa622007-08-15 14:28:22 +0000101
Senthil Kumaranaca8fd72008-06-23 04:41:59 +0000102 import urllib.parse
Georg Brandl48310cd2009-01-03 21:18:54 +0000103 import urllib.request
Georg Brandl116aa622007-08-15 14:28:22 +0000104
105 url = 'http://www.someserver.com/cgi-bin/register.cgi'
106 values = {'name' : 'Michael Foord',
107 'location' : 'Northampton',
108 'language' : 'Python' }
109
Senthil Kumaranaca8fd72008-06-23 04:41:59 +0000110 data = urllib.parse.urlencode(values)
Senthil Kumaran87684e62012-03-14 18:08:13 -0700111 data = data.encode('utf-8') # data should be bytes
Senthil Kumaranaca8fd72008-06-23 04:41:59 +0000112 req = urllib.request.Request(url, data)
113 response = urllib.request.urlopen(req)
Georg Brandl116aa622007-08-15 14:28:22 +0000114 the_page = response.read()
115
116Note that other encodings are sometimes required (e.g. for file upload from HTML
117forms - see `HTML Specification, Form Submission
118<http://www.w3.org/TR/REC-html40/interact/forms.html#h-17.13>`_ for more
119details).
120
Georg Brandl0f7ede42008-06-23 11:23:31 +0000121If you do not pass the ``data`` argument, urllib uses a **GET** request. One
Georg Brandl116aa622007-08-15 14:28:22 +0000122way in which GET and POST requests differ is that POST requests often have
123"side-effects": they change the state of the system in some way (for example by
124placing an order with the website for a hundredweight of tinned spam to be
125delivered to your door). Though the HTTP standard makes it clear that POSTs are
126intended to *always* cause side-effects, and GET requests *never* to cause
127side-effects, nothing prevents a GET request from having side-effects, nor a
128POST requests from having no side-effects. Data can also be passed in an HTTP
129GET request by encoding it in the URL itself.
130
131This is done as follows::
132
Senthil Kumaranaca8fd72008-06-23 04:41:59 +0000133 >>> import urllib.request
134 >>> import urllib.parse
Georg Brandl116aa622007-08-15 14:28:22 +0000135 >>> data = {}
136 >>> data['name'] = 'Somebody Here'
137 >>> data['location'] = 'Northampton'
138 >>> data['language'] = 'Python'
Senthil Kumaranaca8fd72008-06-23 04:41:59 +0000139 >>> url_values = urllib.parse.urlencode(data)
Georg Brandl6911e3c2007-09-04 07:15:32 +0000140 >>> print(url_values)
Georg Brandl116aa622007-08-15 14:28:22 +0000141 name=Somebody+Here&language=Python&location=Northampton
142 >>> url = 'http://www.example.com/example.cgi'
143 >>> full_url = url + '?' + url_values
Georg Brandl06ad13e2011-07-23 08:04:40 +0200144 >>> data = urllib.request.urlopen(full_url)
Georg Brandl116aa622007-08-15 14:28:22 +0000145
146Notice that the full URL is created by adding a ``?`` to the URL, followed by
147the encoded values.
148
149Headers
150-------
151
152We'll discuss here one particular HTTP header, to illustrate how to add headers
153to your HTTP request.
154
155Some websites [#]_ dislike being browsed by programs, or send different versions
Senthil Kumaranaca8fd72008-06-23 04:41:59 +0000156to different browsers [#]_ . By default urllib identifies itself as
Georg Brandl116aa622007-08-15 14:28:22 +0000157``Python-urllib/x.y`` (where ``x`` and ``y`` are the major and minor version
158numbers of the Python release,
159e.g. ``Python-urllib/2.5``), which may confuse the site, or just plain
160not work. The way a browser identifies itself is through the
161``User-Agent`` header [#]_. When you create a Request object you can
162pass a dictionary of headers in. The following example makes the same
163request as above, but identifies itself as a version of Internet
164Explorer [#]_. ::
165
Senthil Kumaranaca8fd72008-06-23 04:41:59 +0000166 import urllib.parse
Georg Brandl48310cd2009-01-03 21:18:54 +0000167 import urllib.request
168
Georg Brandl116aa622007-08-15 14:28:22 +0000169 url = 'http://www.someserver.com/cgi-bin/register.cgi'
Georg Brandl48310cd2009-01-03 21:18:54 +0000170 user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
Georg Brandl116aa622007-08-15 14:28:22 +0000171 values = {'name' : 'Michael Foord',
172 'location' : 'Northampton',
173 'language' : 'Python' }
174 headers = { 'User-Agent' : user_agent }
Georg Brandl48310cd2009-01-03 21:18:54 +0000175
Senthil Kumaran87684e62012-03-14 18:08:13 -0700176 data = urllib.parse.urlencode(values)
177 data = data.encode('utf-8')
Senthil Kumaranaca8fd72008-06-23 04:41:59 +0000178 req = urllib.request.Request(url, data, headers)
179 response = urllib.request.urlopen(req)
Georg Brandl116aa622007-08-15 14:28:22 +0000180 the_page = response.read()
181
182The response also has two useful methods. See the section on `info and geturl`_
183which comes after we have a look at what happens when things go wrong.
184
185
186Handling Exceptions
187===================
188
Georg Brandl22b34312009-07-26 14:54:51 +0000189*urlopen* raises :exc:`URLError` when it cannot handle a response (though as
190usual with Python APIs, built-in exceptions such as :exc:`ValueError`,
191:exc:`TypeError` etc. may also be raised).
Georg Brandl116aa622007-08-15 14:28:22 +0000192
Benjamin Petersone5384b02008-10-04 22:00:42 +0000193:exc:`HTTPError` is the subclass of :exc:`URLError` raised in the specific case of
Georg Brandl116aa622007-08-15 14:28:22 +0000194HTTP URLs.
195
Georg Brandl0f7ede42008-06-23 11:23:31 +0000196The exception classes are exported from the :mod:`urllib.error` module.
197
Georg Brandl116aa622007-08-15 14:28:22 +0000198URLError
199--------
200
201Often, URLError is raised because there is no network connection (no route to
202the specified server), or the specified server doesn't exist. In this case, the
203exception raised will have a 'reason' attribute, which is a tuple containing an
204error code and a text error message.
205
206e.g. ::
207
Senthil Kumaranaca8fd72008-06-23 04:41:59 +0000208 >>> req = urllib.request.Request('http://www.pretend_server.org')
209 >>> try: urllib.request.urlopen(req)
Michael Foord20b50b12009-05-12 11:19:14 +0000210 >>> except urllib.error.URLError as e:
Georg Brandl6911e3c2007-09-04 07:15:32 +0000211 >>> print(e.reason)
Georg Brandl116aa622007-08-15 14:28:22 +0000212 >>>
213 (4, 'getaddrinfo failed')
214
215
216HTTPError
217---------
218
219Every HTTP response from the server contains a numeric "status code". Sometimes
220the status code indicates that the server is unable to fulfil the request. The
221default handlers will handle some of these responses for you (for example, if
222the response is a "redirection" that requests the client fetch the document from
Georg Brandl0f7ede42008-06-23 11:23:31 +0000223a different URL, urllib will handle that for you). For those it can't handle,
Benjamin Petersone5384b02008-10-04 22:00:42 +0000224urlopen will raise an :exc:`HTTPError`. Typical errors include '404' (page not
Georg Brandl116aa622007-08-15 14:28:22 +0000225found), '403' (request forbidden), and '401' (authentication required).
226
227See section 10 of RFC 2616 for a reference on all the HTTP error codes.
228
Benjamin Petersone5384b02008-10-04 22:00:42 +0000229The :exc:`HTTPError` instance raised will have an integer 'code' attribute, which
Georg Brandl116aa622007-08-15 14:28:22 +0000230corresponds to the error sent by the server.
231
232Error Codes
233~~~~~~~~~~~
234
235Because the default handlers handle redirects (codes in the 300 range), and
236codes in the 100-299 range indicate success, you will usually only see error
237codes in the 400-599 range.
238
Georg Brandl24420152008-05-26 16:32:26 +0000239:attr:`http.server.BaseHTTPRequestHandler.responses` is a useful dictionary of
Georg Brandl116aa622007-08-15 14:28:22 +0000240response codes in that shows all the response codes used by RFC 2616. The
241dictionary is reproduced here for convenience ::
242
243 # Table mapping response codes to messages; entries have the
244 # form {code: (shortmessage, longmessage)}.
245 responses = {
246 100: ('Continue', 'Request received, please continue'),
247 101: ('Switching Protocols',
248 'Switching to new protocol; obey Upgrade header'),
249
250 200: ('OK', 'Request fulfilled, document follows'),
251 201: ('Created', 'Document created, URL follows'),
252 202: ('Accepted',
253 'Request accepted, processing continues off-line'),
254 203: ('Non-Authoritative Information', 'Request fulfilled from cache'),
255 204: ('No Content', 'Request fulfilled, nothing follows'),
256 205: ('Reset Content', 'Clear input form for further input.'),
257 206: ('Partial Content', 'Partial content follows.'),
258
259 300: ('Multiple Choices',
260 'Object has several resources -- see URI list'),
261 301: ('Moved Permanently', 'Object moved permanently -- see URI list'),
262 302: ('Found', 'Object moved temporarily -- see URI list'),
263 303: ('See Other', 'Object moved -- see Method and URL list'),
264 304: ('Not Modified',
265 'Document has not changed since given time'),
266 305: ('Use Proxy',
267 'You must use proxy specified in Location to access this '
268 'resource.'),
269 307: ('Temporary Redirect',
270 'Object moved temporarily -- see URI list'),
271
272 400: ('Bad Request',
273 'Bad request syntax or unsupported method'),
274 401: ('Unauthorized',
275 'No permission -- see authorization schemes'),
276 402: ('Payment Required',
277 'No payment -- see charging schemes'),
278 403: ('Forbidden',
279 'Request forbidden -- authorization will not help'),
280 404: ('Not Found', 'Nothing matches the given URI'),
281 405: ('Method Not Allowed',
282 'Specified method is invalid for this server.'),
283 406: ('Not Acceptable', 'URI not available in preferred format.'),
284 407: ('Proxy Authentication Required', 'You must authenticate with '
285 'this proxy before proceeding.'),
286 408: ('Request Timeout', 'Request timed out; try again later.'),
287 409: ('Conflict', 'Request conflict.'),
288 410: ('Gone',
289 'URI no longer exists and has been permanently removed.'),
290 411: ('Length Required', 'Client must specify Content-Length.'),
291 412: ('Precondition Failed', 'Precondition in headers is false.'),
292 413: ('Request Entity Too Large', 'Entity is too large.'),
293 414: ('Request-URI Too Long', 'URI is too long.'),
294 415: ('Unsupported Media Type', 'Entity body in unsupported format.'),
295 416: ('Requested Range Not Satisfiable',
296 'Cannot satisfy request range.'),
297 417: ('Expectation Failed',
298 'Expect condition could not be satisfied.'),
299
300 500: ('Internal Server Error', 'Server got itself in trouble'),
301 501: ('Not Implemented',
302 'Server does not support this operation'),
303 502: ('Bad Gateway', 'Invalid responses from another server/proxy.'),
304 503: ('Service Unavailable',
305 'The server cannot process the request due to a high load'),
306 504: ('Gateway Timeout',
307 'The gateway server did not receive a timely response'),
308 505: ('HTTP Version Not Supported', 'Cannot fulfill request.'),
309 }
310
311When an error is raised the server responds by returning an HTTP error code
Benjamin Petersone5384b02008-10-04 22:00:42 +0000312*and* an error page. You can use the :exc:`HTTPError` instance as a response on the
Georg Brandl116aa622007-08-15 14:28:22 +0000313page returned. This means that as well as the code attribute, it also has read,
Senthil Kumaranaca8fd72008-06-23 04:41:59 +0000314geturl, and info, methods as returned by the ``urllib.response`` module::
Georg Brandl116aa622007-08-15 14:28:22 +0000315
Senthil Kumaranaca8fd72008-06-23 04:41:59 +0000316 >>> req = urllib.request.Request('http://www.python.org/fish.html')
Georg Brandl48310cd2009-01-03 21:18:54 +0000317 >>> try:
Senthil Kumaranaca8fd72008-06-23 04:41:59 +0000318 >>> urllib.request.urlopen(req)
Georg Brandlfe5f4092009-05-22 10:44:31 +0000319 >>> except urllib.error.HTTPError as e:
Georg Brandl6911e3c2007-09-04 07:15:32 +0000320 >>> print(e.code)
321 >>> print(e.read())
Georg Brandl48310cd2009-01-03 21:18:54 +0000322 >>>
Georg Brandl116aa622007-08-15 14:28:22 +0000323 404
Georg Brandl48310cd2009-01-03 21:18:54 +0000324 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
Georg Brandl116aa622007-08-15 14:28:22 +0000325 "http://www.w3.org/TR/html4/loose.dtd">
Georg Brandl48310cd2009-01-03 21:18:54 +0000326 <?xml-stylesheet href="./css/ht2html.css"
Georg Brandl116aa622007-08-15 14:28:22 +0000327 type="text/css"?>
Georg Brandl48310cd2009-01-03 21:18:54 +0000328 <html><head><title>Error 404: File Not Found</title>
Georg Brandl116aa622007-08-15 14:28:22 +0000329 ...... etc...
330
331Wrapping it Up
332--------------
333
Benjamin Petersone5384b02008-10-04 22:00:42 +0000334So if you want to be prepared for :exc:`HTTPError` *or* :exc:`URLError` there are two
Georg Brandl116aa622007-08-15 14:28:22 +0000335basic approaches. I prefer the second approach.
336
337Number 1
338~~~~~~~~
339
340::
341
342
Senthil Kumaranaca8fd72008-06-23 04:41:59 +0000343 from urllib.request import Request, urlopen
344 from urllib.error import URLError, HTTPError
Georg Brandl116aa622007-08-15 14:28:22 +0000345 req = Request(someurl)
346 try:
347 response = urlopen(req)
Michael Foord20b50b12009-05-12 11:19:14 +0000348 except HTTPError as e:
Georg Brandl6911e3c2007-09-04 07:15:32 +0000349 print('The server couldn\'t fulfill the request.')
350 print('Error code: ', e.code)
Michael Foord20b50b12009-05-12 11:19:14 +0000351 except URLError as e:
Georg Brandl6911e3c2007-09-04 07:15:32 +0000352 print('We failed to reach a server.')
353 print('Reason: ', e.reason)
Georg Brandl116aa622007-08-15 14:28:22 +0000354 else:
355 # everything is fine
356
357
358.. note::
359
360 The ``except HTTPError`` *must* come first, otherwise ``except URLError``
Benjamin Petersone5384b02008-10-04 22:00:42 +0000361 will *also* catch an :exc:`HTTPError`.
Georg Brandl116aa622007-08-15 14:28:22 +0000362
363Number 2
364~~~~~~~~
365
366::
367
Senthil Kumaranaca8fd72008-06-23 04:41:59 +0000368 from urllib.request import Request, urlopen
369 from urllib.error import URLError
Georg Brandl116aa622007-08-15 14:28:22 +0000370 req = Request(someurl)
371 try:
372 response = urlopen(req)
Michael Foord20b50b12009-05-12 11:19:14 +0000373 except URLError as e:
Georg Brandl116aa622007-08-15 14:28:22 +0000374 if hasattr(e, 'reason'):
Georg Brandl6911e3c2007-09-04 07:15:32 +0000375 print('We failed to reach a server.')
376 print('Reason: ', e.reason)
Georg Brandl116aa622007-08-15 14:28:22 +0000377 elif hasattr(e, 'code'):
Georg Brandl6911e3c2007-09-04 07:15:32 +0000378 print('The server couldn\'t fulfill the request.')
379 print('Error code: ', e.code)
Georg Brandl116aa622007-08-15 14:28:22 +0000380 else:
381 # everything is fine
Georg Brandl48310cd2009-01-03 21:18:54 +0000382
Georg Brandl116aa622007-08-15 14:28:22 +0000383
384info and geturl
385===============
386
Benjamin Petersone5384b02008-10-04 22:00:42 +0000387The response returned by urlopen (or the :exc:`HTTPError` instance) has two
388useful methods :meth:`info` and :meth:`geturl` and is defined in the module
389:mod:`urllib.response`..
Georg Brandl116aa622007-08-15 14:28:22 +0000390
391**geturl** - this returns the real URL of the page fetched. This is useful
392because ``urlopen`` (or the opener object used) may have followed a
393redirect. The URL of the page fetched may not be the same as the URL requested.
394
395**info** - this returns a dictionary-like object that describes the page
396fetched, particularly the headers sent by the server. It is currently an
Georg Brandl0f7ede42008-06-23 11:23:31 +0000397:class:`http.client.HTTPMessage` instance.
Georg Brandl116aa622007-08-15 14:28:22 +0000398
399Typical headers include 'Content-length', 'Content-type', and so on. See the
400`Quick Reference to HTTP Headers <http://www.cs.tut.fi/~jkorpela/http.html>`_
401for a useful listing of HTTP headers with brief explanations of their meaning
402and use.
403
404
405Openers and Handlers
406====================
407
408When you fetch a URL you use an opener (an instance of the perhaps
Senthil Kumaranaca8fd72008-06-23 04:41:59 +0000409confusingly-named :class:`urllib.request.OpenerDirector`). Normally we have been using
Georg Brandl116aa622007-08-15 14:28:22 +0000410the default opener - via ``urlopen`` - but you can create custom
411openers. Openers use handlers. All the "heavy lifting" is done by the
412handlers. Each handler knows how to open URLs for a particular URL scheme (http,
413ftp, etc.), or how to handle an aspect of URL opening, for example HTTP
414redirections or HTTP cookies.
415
416You will want to create openers if you want to fetch URLs with specific handlers
417installed, for example to get an opener that handles cookies, or to get an
418opener that does not handle redirections.
419
420To create an opener, instantiate an ``OpenerDirector``, and then call
421``.add_handler(some_handler_instance)`` repeatedly.
422
423Alternatively, you can use ``build_opener``, which is a convenience function for
424creating opener objects with a single function call. ``build_opener`` adds
425several handlers by default, but provides a quick way to add more and/or
426override the default handlers.
427
428Other sorts of handlers you might want to can handle proxies, authentication,
429and other common but slightly specialised situations.
430
431``install_opener`` can be used to make an ``opener`` object the (global) default
432opener. This means that calls to ``urlopen`` will use the opener you have
433installed.
434
435Opener objects have an ``open`` method, which can be called directly to fetch
436urls in the same way as the ``urlopen`` function: there's no need to call
437``install_opener``, except as a convenience.
438
439
440Basic Authentication
441====================
442
443To illustrate creating and installing a handler we will use the
444``HTTPBasicAuthHandler``. For a more detailed discussion of this subject --
445including an explanation of how Basic Authentication works - see the `Basic
446Authentication Tutorial
447<http://www.voidspace.org.uk/python/articles/authentication.shtml>`_.
448
449When authentication is required, the server sends a header (as well as the 401
450error code) requesting authentication. This specifies the authentication scheme
451and a 'realm'. The header looks like : ``Www-authenticate: SCHEME
452realm="REALM"``.
453
Georg Brandl48310cd2009-01-03 21:18:54 +0000454e.g. ::
Georg Brandl116aa622007-08-15 14:28:22 +0000455
456 Www-authenticate: Basic realm="cPanel Users"
457
458
459The client should then retry the request with the appropriate name and password
460for the realm included as a header in the request. This is 'basic
461authentication'. In order to simplify this process we can create an instance of
462``HTTPBasicAuthHandler`` and an opener to use this handler.
463
464The ``HTTPBasicAuthHandler`` uses an object called a password manager to handle
465the mapping of URLs and realms to passwords and usernames. If you know what the
466realm is (from the authentication header sent by the server), then you can use a
467``HTTPPasswordMgr``. Frequently one doesn't care what the realm is. In that
468case, it is convenient to use ``HTTPPasswordMgrWithDefaultRealm``. This allows
469you to specify a default username and password for a URL. This will be supplied
470in the absence of you providing an alternative combination for a specific
471realm. We indicate this by providing ``None`` as the realm argument to the
472``add_password`` method.
473
474The top-level URL is the first URL that requires authentication. URLs "deeper"
475than the URL you pass to .add_password() will also match. ::
476
477 # create a password manager
Georg Brandl48310cd2009-01-03 21:18:54 +0000478 password_mgr = urllib.request.HTTPPasswordMgrWithDefaultRealm()
Georg Brandl116aa622007-08-15 14:28:22 +0000479
480 # Add the username and password.
Georg Brandl1f01deb2009-01-03 22:47:39 +0000481 # If we knew the realm, we could use it instead of None.
Georg Brandl116aa622007-08-15 14:28:22 +0000482 top_level_url = "http://example.com/foo/"
483 password_mgr.add_password(None, top_level_url, username, password)
484
Georg Brandl48310cd2009-01-03 21:18:54 +0000485 handler = urllib.request.HTTPBasicAuthHandler(password_mgr)
Georg Brandl116aa622007-08-15 14:28:22 +0000486
487 # create "opener" (OpenerDirector instance)
Georg Brandl48310cd2009-01-03 21:18:54 +0000488 opener = urllib.request.build_opener(handler)
Georg Brandl116aa622007-08-15 14:28:22 +0000489
490 # use the opener to fetch a URL
Georg Brandl48310cd2009-01-03 21:18:54 +0000491 opener.open(a_url)
Georg Brandl116aa622007-08-15 14:28:22 +0000492
493 # Install the opener.
Senthil Kumaranaca8fd72008-06-23 04:41:59 +0000494 # Now all calls to urllib.request.urlopen use our opener.
Georg Brandl48310cd2009-01-03 21:18:54 +0000495 urllib.request.install_opener(opener)
Georg Brandl116aa622007-08-15 14:28:22 +0000496
497.. note::
498
Ezio Melotti8e87fec2009-07-21 20:37:52 +0000499 In the above example we only supplied our ``HTTPBasicAuthHandler`` to
Georg Brandl116aa622007-08-15 14:28:22 +0000500 ``build_opener``. By default openers have the handlers for normal situations
501 -- ``ProxyHandler``, ``UnknownHandler``, ``HTTPHandler``,
502 ``HTTPDefaultErrorHandler``, ``HTTPRedirectHandler``, ``FTPHandler``,
503 ``FileHandler``, ``HTTPErrorProcessor``.
504
505``top_level_url`` is in fact *either* a full URL (including the 'http:' scheme
506component and the hostname and optionally the port number)
507e.g. "http://example.com/" *or* an "authority" (i.e. the hostname,
508optionally including the port number) e.g. "example.com" or "example.com:8080"
509(the latter example includes a port number). The authority, if present, must
510NOT contain the "userinfo" component - for example "joe@password:example.com" is
511not correct.
512
513
514Proxies
515=======
516
Georg Brandl0f7ede42008-06-23 11:23:31 +0000517**urllib** will auto-detect your proxy settings and use those. This is through
Georg Brandl116aa622007-08-15 14:28:22 +0000518the ``ProxyHandler`` which is part of the normal handler chain. Normally that's
519a good thing, but there are occasions when it may not be helpful [#]_. One way
520to do this is to setup our own ``ProxyHandler``, with no proxies defined. This
521is done using similar steps to setting up a `Basic Authentication`_ handler : ::
522
Senthil Kumaranaca8fd72008-06-23 04:41:59 +0000523 >>> proxy_support = urllib.request.ProxyHandler({})
524 >>> opener = urllib.request.build_opener(proxy_support)
525 >>> urllib.request.install_opener(opener)
Georg Brandl116aa622007-08-15 14:28:22 +0000526
527.. note::
528
Senthil Kumaranaca8fd72008-06-23 04:41:59 +0000529 Currently ``urllib.request`` *does not* support fetching of ``https`` locations
530 through a proxy. However, this can be enabled by extending urllib.request as
Georg Brandl116aa622007-08-15 14:28:22 +0000531 shown in the recipe [#]_.
532
533
534Sockets and Layers
535==================
536
Georg Brandl0f7ede42008-06-23 11:23:31 +0000537The Python support for fetching resources from the web is layered. urllib uses
538the :mod:`http.client` library, which in turn uses the socket library.
Georg Brandl116aa622007-08-15 14:28:22 +0000539
540As of Python 2.3 you can specify how long a socket should wait for a response
541before timing out. This can be useful in applications which have to fetch web
542pages. By default the socket module has *no timeout* and can hang. Currently,
Senthil Kumaranaca8fd72008-06-23 04:41:59 +0000543the socket timeout is not exposed at the http.client or urllib.request levels.
Georg Brandl24420152008-05-26 16:32:26 +0000544However, you can set the default timeout globally for all sockets using ::
Georg Brandl116aa622007-08-15 14:28:22 +0000545
546 import socket
Senthil Kumaranaca8fd72008-06-23 04:41:59 +0000547 import urllib.request
Georg Brandl116aa622007-08-15 14:28:22 +0000548
549 # timeout in seconds
550 timeout = 10
Georg Brandl48310cd2009-01-03 21:18:54 +0000551 socket.setdefaulttimeout(timeout)
Georg Brandl116aa622007-08-15 14:28:22 +0000552
Senthil Kumaranaca8fd72008-06-23 04:41:59 +0000553 # this call to urllib.request.urlopen now uses the default timeout
Georg Brandl116aa622007-08-15 14:28:22 +0000554 # we have set in the socket module
Senthil Kumaranaca8fd72008-06-23 04:41:59 +0000555 req = urllib.request.Request('http://www.voidspace.org.uk')
556 response = urllib.request.urlopen(req)
Georg Brandl116aa622007-08-15 14:28:22 +0000557
558
559-------
560
561
562Footnotes
563=========
564
565This document was reviewed and revised by John Lee.
566
567.. [#] For an introduction to the CGI protocol see
Georg Brandl48310cd2009-01-03 21:18:54 +0000568 `Writing Web Applications in Python <http://www.pyzine.com/Issue008/Section_Articles/article_CGIOne.html>`_.
Georg Brandl116aa622007-08-15 14:28:22 +0000569.. [#] Like Google for example. The *proper* way to use google from a program
570 is to use `PyGoogle <http://pygoogle.sourceforge.net>`_ of course. See
571 `Voidspace Google <http://www.voidspace.org.uk/python/recipebook.shtml#google>`_
572 for some examples of using the Google API.
573.. [#] Browser sniffing is a very bad practise for website design - building
574 sites using web standards is much more sensible. Unfortunately a lot of
575 sites still send different versions to different browsers.
576.. [#] The user agent for MSIE 6 is
577 *'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322)'*
578.. [#] For details of more HTTP request headers, see
579 `Quick Reference to HTTP Headers`_.
580.. [#] In my case I have to use a proxy to access the internet at work. If you
581 attempt to fetch *localhost* URLs through this proxy it blocks them. IE
Georg Brandl0f7ede42008-06-23 11:23:31 +0000582 is set to use the proxy, which urllib picks up on. In order to test
583 scripts with a localhost server, I have to prevent urllib from using
Georg Brandl116aa622007-08-15 14:28:22 +0000584 the proxy.
Georg Brandl48310cd2009-01-03 21:18:54 +0000585.. [#] urllib opener for SSL proxy (CONNECT method): `ASPN Cookbook Recipe
Georg Brandl116aa622007-08-15 14:28:22 +0000586 <http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/456195>`_.
Georg Brandl48310cd2009-01-03 21:18:54 +0000587