blob: c1fd5cf0680d96cec292a8533e551de93f3319be [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
Georg Brandle73778c2014-10-29 08:36:35 +010029**urllib.request** is a Python 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
Serhiy Storchakad97b7dc2017-05-16 23:18:09 +030037before the ``":"`` in URL - for example ``"ftp"`` is the URL scheme of
38``"ftp://python.org/"``) using their associated network protocols (e.g. FTP, HTTP).
Georg Brandl116aa622007-08-15 14:28:22 +000039This 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
Berker Peksag9575e182015-04-12 13:52:49 +030056 with urllib.request.urlopen('http://python.org/') as response:
57 html = response.read()
Georg Brandl116aa622007-08-15 14:28:22 +000058
Senthil Kumarane24f96a2012-03-13 19:29:33 -070059If you wish to retrieve a resource via URL and store it in a temporary location,
Serhiy Storchakabfdcd432013-10-13 23:09:14 +030060you can do so via the :func:`~urllib.request.urlretrieve` function::
Senthil Kumarane24f96a2012-03-13 19:29:33 -070061
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
Martin Panter6245cb32016-04-15 02:14:19 +000067could have used a URL starting with 'ftp:', 'file:', etc.). However, it's the
Georg Brandl116aa622007-08-15 14:28:22 +000068purpose 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')
Berker Peksag9575e182015-04-12 13:52:49 +030082 with urllib.request.urlopen(req) as response:
83 the_page = response.read()
Georg Brandl116aa622007-08-15 14:28:22 +000084
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
Berker Peksagfd6400a2014-07-01 06:02:42 +0300100(Common Gateway Interface) script or other web application). With HTTP,
Georg Brandl116aa622007-08-15 14:28:22 +0000101this 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)
Martin Pantercda85a02015-11-24 22:33:18 +0000118 data = data.encode('ascii') # data should be bytes
Senthil Kumaranaca8fd72008-06-23 04:41:59 +0000119 req = urllib.request.Request(url, data)
Berker Peksag9575e182015-04-12 13:52:49 +0300120 with urllib.request.urlopen(req) as response:
121 the_page = response.read()
Georg Brandl116aa622007-08-15 14:28:22 +0000122
123Note that other encodings are sometimes required (e.g. for file upload from HTML
124forms - see `HTML Specification, Form Submission
Serhiy Storchaka6dff0202016-05-07 10:49:07 +0300125<https://www.w3.org/TR/REC-html40/interact/forms.html#h-17.13>`_ for more
Georg Brandl116aa622007-08-15 14:28:22 +0000126details).
127
Georg Brandl0f7ede42008-06-23 11:23:31 +0000128If you do not pass the ``data`` argument, urllib uses a **GET** request. One
Georg Brandl116aa622007-08-15 14:28:22 +0000129way in which GET and POST requests differ is that POST requests often have
130"side-effects": they change the state of the system in some way (for example by
131placing an order with the website for a hundredweight of tinned spam to be
132delivered to your door). Though the HTTP standard makes it clear that POSTs are
133intended to *always* cause side-effects, and GET requests *never* to cause
134side-effects, nothing prevents a GET request from having side-effects, nor a
135POST requests from having no side-effects. Data can also be passed in an HTTP
136GET request by encoding it in the URL itself.
137
138This is done as follows::
139
Senthil Kumaranaca8fd72008-06-23 04:41:59 +0000140 >>> import urllib.request
141 >>> import urllib.parse
Georg Brandl116aa622007-08-15 14:28:22 +0000142 >>> data = {}
143 >>> data['name'] = 'Somebody Here'
144 >>> data['location'] = 'Northampton'
145 >>> data['language'] = 'Python'
Senthil Kumaranaca8fd72008-06-23 04:41:59 +0000146 >>> url_values = urllib.parse.urlencode(data)
Senthil Kumaran570bc4c2012-10-09 00:38:17 -0700147 >>> print(url_values) # The order may differ from below. #doctest: +SKIP
Georg Brandl116aa622007-08-15 14:28:22 +0000148 name=Somebody+Here&language=Python&location=Northampton
149 >>> url = 'http://www.example.com/example.cgi'
150 >>> full_url = url + '?' + url_values
Georg Brandl06ad13e2011-07-23 08:04:40 +0200151 >>> data = urllib.request.urlopen(full_url)
Georg Brandl116aa622007-08-15 14:28:22 +0000152
153Notice that the full URL is created by adding a ``?`` to the URL, followed by
154the encoded values.
155
156Headers
157-------
158
159We'll discuss here one particular HTTP header, to illustrate how to add headers
160to your HTTP request.
161
162Some websites [#]_ dislike being browsed by programs, or send different versions
Serhiy Storchakaa4d170d2013-12-23 18:20:51 +0200163to different browsers [#]_. By default urllib identifies itself as
Georg Brandl116aa622007-08-15 14:28:22 +0000164``Python-urllib/x.y`` (where ``x`` and ``y`` are the major and minor version
165numbers of the Python release,
166e.g. ``Python-urllib/2.5``), which may confuse the site, or just plain
167not work. The way a browser identifies itself is through the
168``User-Agent`` header [#]_. When you create a Request object you can
169pass a dictionary of headers in. The following example makes the same
170request as above, but identifies itself as a version of Internet
171Explorer [#]_. ::
172
Senthil Kumaranaca8fd72008-06-23 04:41:59 +0000173 import urllib.parse
Georg Brandl48310cd2009-01-03 21:18:54 +0000174 import urllib.request
175
Georg Brandl116aa622007-08-15 14:28:22 +0000176 url = 'http://www.someserver.com/cgi-bin/register.cgi'
Benjamin Peterson95acbce2015-09-20 23:16:45 +0500177 user_agent = 'Mozilla/5.0 (Windows NT 6.1; Win64; x64)'
Serhiy Storchakadba90392016-05-10 12:01:23 +0300178 values = {'name': 'Michael Foord',
179 'location': 'Northampton',
180 'language': 'Python' }
181 headers = {'User-Agent': user_agent}
Georg Brandl48310cd2009-01-03 21:18:54 +0000182
Martin Pantercda85a02015-11-24 22:33:18 +0000183 data = urllib.parse.urlencode(values)
184 data = data.encode('ascii')
Senthil Kumaranaca8fd72008-06-23 04:41:59 +0000185 req = urllib.request.Request(url, data, headers)
Berker Peksag9575e182015-04-12 13:52:49 +0300186 with urllib.request.urlopen(req) as response:
187 the_page = response.read()
Georg Brandl116aa622007-08-15 14:28:22 +0000188
189The response also has two useful methods. See the section on `info and geturl`_
190which comes after we have a look at what happens when things go wrong.
191
192
193Handling Exceptions
194===================
195
Georg Brandl22b34312009-07-26 14:54:51 +0000196*urlopen* raises :exc:`URLError` when it cannot handle a response (though as
197usual with Python APIs, built-in exceptions such as :exc:`ValueError`,
198:exc:`TypeError` etc. may also be raised).
Georg Brandl116aa622007-08-15 14:28:22 +0000199
Benjamin Petersone5384b02008-10-04 22:00:42 +0000200:exc:`HTTPError` is the subclass of :exc:`URLError` raised in the specific case of
Georg Brandl116aa622007-08-15 14:28:22 +0000201HTTP URLs.
202
Georg Brandl0f7ede42008-06-23 11:23:31 +0000203The exception classes are exported from the :mod:`urllib.error` module.
204
Georg Brandl116aa622007-08-15 14:28:22 +0000205URLError
206--------
207
208Often, URLError is raised because there is no network connection (no route to
209the specified server), or the specified server doesn't exist. In this case, the
210exception raised will have a 'reason' attribute, which is a tuple containing an
211error code and a text error message.
212
213e.g. ::
214
Senthil Kumaranaca8fd72008-06-23 04:41:59 +0000215 >>> req = urllib.request.Request('http://www.pretend_server.org')
216 >>> try: urllib.request.urlopen(req)
Senthil Kumaran570bc4c2012-10-09 00:38:17 -0700217 ... except urllib.error.URLError as e:
Serhiy Storchakadba90392016-05-10 12:01:23 +0300218 ... print(e.reason) #doctest: +SKIP
Senthil Kumaran570bc4c2012-10-09 00:38:17 -0700219 ...
Georg Brandl116aa622007-08-15 14:28:22 +0000220 (4, 'getaddrinfo failed')
221
222
223HTTPError
224---------
225
226Every HTTP response from the server contains a numeric "status code". Sometimes
227the status code indicates that the server is unable to fulfil the request. The
228default handlers will handle some of these responses for you (for example, if
229the response is a "redirection" that requests the client fetch the document from
Georg Brandl0f7ede42008-06-23 11:23:31 +0000230a different URL, urllib will handle that for you). For those it can't handle,
Benjamin Petersone5384b02008-10-04 22:00:42 +0000231urlopen will raise an :exc:`HTTPError`. Typical errors include '404' (page not
Georg Brandl116aa622007-08-15 14:28:22 +0000232found), '403' (request forbidden), and '401' (authentication required).
233
234See section 10 of RFC 2616 for a reference on all the HTTP error codes.
235
Benjamin Petersone5384b02008-10-04 22:00:42 +0000236The :exc:`HTTPError` instance raised will have an integer 'code' attribute, which
Georg Brandl116aa622007-08-15 14:28:22 +0000237corresponds to the error sent by the server.
238
239Error Codes
240~~~~~~~~~~~
241
242Because the default handlers handle redirects (codes in the 300 range), and
Serhiy Storchakac7b1a0b2016-11-26 13:43:28 +0200243codes in the 100--299 range indicate success, you will usually only see error
244codes in the 400--599 range.
Georg Brandl116aa622007-08-15 14:28:22 +0000245
Georg Brandl24420152008-05-26 16:32:26 +0000246:attr:`http.server.BaseHTTPRequestHandler.responses` is a useful dictionary of
Georg Brandl116aa622007-08-15 14:28:22 +0000247response codes in that shows all the response codes used by RFC 2616. The
248dictionary is reproduced here for convenience ::
249
250 # Table mapping response codes to messages; entries have the
251 # form {code: (shortmessage, longmessage)}.
252 responses = {
253 100: ('Continue', 'Request received, please continue'),
254 101: ('Switching Protocols',
255 'Switching to new protocol; obey Upgrade header'),
256
257 200: ('OK', 'Request fulfilled, document follows'),
258 201: ('Created', 'Document created, URL follows'),
259 202: ('Accepted',
260 'Request accepted, processing continues off-line'),
261 203: ('Non-Authoritative Information', 'Request fulfilled from cache'),
262 204: ('No Content', 'Request fulfilled, nothing follows'),
263 205: ('Reset Content', 'Clear input form for further input.'),
264 206: ('Partial Content', 'Partial content follows.'),
265
266 300: ('Multiple Choices',
267 'Object has several resources -- see URI list'),
268 301: ('Moved Permanently', 'Object moved permanently -- see URI list'),
269 302: ('Found', 'Object moved temporarily -- see URI list'),
270 303: ('See Other', 'Object moved -- see Method and URL list'),
271 304: ('Not Modified',
272 'Document has not changed since given time'),
273 305: ('Use Proxy',
274 'You must use proxy specified in Location to access this '
275 'resource.'),
276 307: ('Temporary Redirect',
277 'Object moved temporarily -- see URI list'),
278
279 400: ('Bad Request',
280 'Bad request syntax or unsupported method'),
281 401: ('Unauthorized',
282 'No permission -- see authorization schemes'),
283 402: ('Payment Required',
284 'No payment -- see charging schemes'),
285 403: ('Forbidden',
286 'Request forbidden -- authorization will not help'),
287 404: ('Not Found', 'Nothing matches the given URI'),
288 405: ('Method Not Allowed',
289 'Specified method is invalid for this server.'),
290 406: ('Not Acceptable', 'URI not available in preferred format.'),
291 407: ('Proxy Authentication Required', 'You must authenticate with '
292 'this proxy before proceeding.'),
293 408: ('Request Timeout', 'Request timed out; try again later.'),
294 409: ('Conflict', 'Request conflict.'),
295 410: ('Gone',
296 'URI no longer exists and has been permanently removed.'),
297 411: ('Length Required', 'Client must specify Content-Length.'),
298 412: ('Precondition Failed', 'Precondition in headers is false.'),
299 413: ('Request Entity Too Large', 'Entity is too large.'),
300 414: ('Request-URI Too Long', 'URI is too long.'),
301 415: ('Unsupported Media Type', 'Entity body in unsupported format.'),
302 416: ('Requested Range Not Satisfiable',
303 'Cannot satisfy request range.'),
304 417: ('Expectation Failed',
305 'Expect condition could not be satisfied.'),
306
307 500: ('Internal Server Error', 'Server got itself in trouble'),
308 501: ('Not Implemented',
309 'Server does not support this operation'),
310 502: ('Bad Gateway', 'Invalid responses from another server/proxy.'),
311 503: ('Service Unavailable',
312 'The server cannot process the request due to a high load'),
313 504: ('Gateway Timeout',
314 'The gateway server did not receive a timely response'),
315 505: ('HTTP Version Not Supported', 'Cannot fulfill request.'),
316 }
317
318When an error is raised the server responds by returning an HTTP error code
Benjamin Petersone5384b02008-10-04 22:00:42 +0000319*and* an error page. You can use the :exc:`HTTPError` instance as a response on the
Georg Brandl116aa622007-08-15 14:28:22 +0000320page returned. This means that as well as the code attribute, it also has read,
Senthil Kumaranaca8fd72008-06-23 04:41:59 +0000321geturl, and info, methods as returned by the ``urllib.response`` module::
Georg Brandl116aa622007-08-15 14:28:22 +0000322
Senthil Kumaranaca8fd72008-06-23 04:41:59 +0000323 >>> req = urllib.request.Request('http://www.python.org/fish.html')
Georg Brandl48310cd2009-01-03 21:18:54 +0000324 >>> try:
Senthil Kumaran570bc4c2012-10-09 00:38:17 -0700325 ... urllib.request.urlopen(req)
326 ... except urllib.error.HTTPError as e:
327 ... print(e.code)
328 ... print(e.read()) #doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
329 ...
Georg Brandl116aa622007-08-15 14:28:22 +0000330 404
Senthil Kumaran570bc4c2012-10-09 00:38:17 -0700331 b'<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
332 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">\n\n\n<html
333 ...
334 <title>Page Not Found</title>\n
335 ...
Georg Brandl116aa622007-08-15 14:28:22 +0000336
337Wrapping it Up
338--------------
339
Benjamin Petersone5384b02008-10-04 22:00:42 +0000340So if you want to be prepared for :exc:`HTTPError` *or* :exc:`URLError` there are two
Georg Brandl116aa622007-08-15 14:28:22 +0000341basic approaches. I prefer the second approach.
342
343Number 1
344~~~~~~~~
345
346::
347
348
Senthil Kumaranaca8fd72008-06-23 04:41:59 +0000349 from urllib.request import Request, urlopen
350 from urllib.error import URLError, HTTPError
Georg Brandl116aa622007-08-15 14:28:22 +0000351 req = Request(someurl)
352 try:
353 response = urlopen(req)
Michael Foord20b50b12009-05-12 11:19:14 +0000354 except HTTPError as e:
Georg Brandl6911e3c2007-09-04 07:15:32 +0000355 print('The server couldn\'t fulfill the request.')
356 print('Error code: ', e.code)
Michael Foord20b50b12009-05-12 11:19:14 +0000357 except URLError as e:
Georg Brandl6911e3c2007-09-04 07:15:32 +0000358 print('We failed to reach a server.')
359 print('Reason: ', e.reason)
Georg Brandl116aa622007-08-15 14:28:22 +0000360 else:
361 # everything is fine
362
363
364.. note::
365
366 The ``except HTTPError`` *must* come first, otherwise ``except URLError``
Benjamin Petersone5384b02008-10-04 22:00:42 +0000367 will *also* catch an :exc:`HTTPError`.
Georg Brandl116aa622007-08-15 14:28:22 +0000368
369Number 2
370~~~~~~~~
371
372::
373
Senthil Kumaranaca8fd72008-06-23 04:41:59 +0000374 from urllib.request import Request, urlopen
Serhiy Storchakadba90392016-05-10 12:01:23 +0300375 from urllib.error import URLError
Georg Brandl116aa622007-08-15 14:28:22 +0000376 req = Request(someurl)
377 try:
378 response = urlopen(req)
Michael Foord20b50b12009-05-12 11:19:14 +0000379 except URLError as e:
Georg Brandl116aa622007-08-15 14:28:22 +0000380 if hasattr(e, 'reason'):
Georg Brandl6911e3c2007-09-04 07:15:32 +0000381 print('We failed to reach a server.')
382 print('Reason: ', e.reason)
Georg Brandl116aa622007-08-15 14:28:22 +0000383 elif hasattr(e, 'code'):
Georg Brandl6911e3c2007-09-04 07:15:32 +0000384 print('The server couldn\'t fulfill the request.')
385 print('Error code: ', e.code)
Georg Brandl116aa622007-08-15 14:28:22 +0000386 else:
387 # everything is fine
Georg Brandl48310cd2009-01-03 21:18:54 +0000388
Georg Brandl116aa622007-08-15 14:28:22 +0000389
390info and geturl
391===============
392
Benjamin Petersone5384b02008-10-04 22:00:42 +0000393The response returned by urlopen (or the :exc:`HTTPError` instance) has two
394useful methods :meth:`info` and :meth:`geturl` and is defined in the module
395:mod:`urllib.response`..
Georg Brandl116aa622007-08-15 14:28:22 +0000396
397**geturl** - this returns the real URL of the page fetched. This is useful
398because ``urlopen`` (or the opener object used) may have followed a
399redirect. The URL of the page fetched may not be the same as the URL requested.
400
401**info** - this returns a dictionary-like object that describes the page
402fetched, particularly the headers sent by the server. It is currently an
Georg Brandl0f7ede42008-06-23 11:23:31 +0000403:class:`http.client.HTTPMessage` instance.
Georg Brandl116aa622007-08-15 14:28:22 +0000404
405Typical headers include 'Content-length', 'Content-type', and so on. See the
Sanyam Khurana338cd832018-01-20 05:55:37 +0530406`Quick Reference to HTTP Headers <http://jkorpela.fi/http.html>`_
Georg Brandl116aa622007-08-15 14:28:22 +0000407for a useful listing of HTTP headers with brief explanations of their meaning
408and use.
409
410
411Openers and Handlers
412====================
413
414When you fetch a URL you use an opener (an instance of the perhaps
Senthil Kumaranaca8fd72008-06-23 04:41:59 +0000415confusingly-named :class:`urllib.request.OpenerDirector`). Normally we have been using
Georg Brandl116aa622007-08-15 14:28:22 +0000416the default opener - via ``urlopen`` - but you can create custom
417openers. Openers use handlers. All the "heavy lifting" is done by the
418handlers. Each handler knows how to open URLs for a particular URL scheme (http,
419ftp, etc.), or how to handle an aspect of URL opening, for example HTTP
420redirections or HTTP cookies.
421
422You will want to create openers if you want to fetch URLs with specific handlers
423installed, for example to get an opener that handles cookies, or to get an
424opener that does not handle redirections.
425
426To create an opener, instantiate an ``OpenerDirector``, and then call
427``.add_handler(some_handler_instance)`` repeatedly.
428
429Alternatively, you can use ``build_opener``, which is a convenience function for
430creating opener objects with a single function call. ``build_opener`` adds
431several handlers by default, but provides a quick way to add more and/or
432override the default handlers.
433
434Other sorts of handlers you might want to can handle proxies, authentication,
435and other common but slightly specialised situations.
436
437``install_opener`` can be used to make an ``opener`` object the (global) default
438opener. This means that calls to ``urlopen`` will use the opener you have
439installed.
440
441Opener objects have an ``open`` method, which can be called directly to fetch
442urls in the same way as the ``urlopen`` function: there's no need to call
443``install_opener``, except as a convenience.
444
445
446Basic Authentication
447====================
448
449To illustrate creating and installing a handler we will use the
450``HTTPBasicAuthHandler``. For a more detailed discussion of this subject --
451including an explanation of how Basic Authentication works - see the `Basic
452Authentication Tutorial
453<http://www.voidspace.org.uk/python/articles/authentication.shtml>`_.
454
455When authentication is required, the server sends a header (as well as the 401
456error code) requesting authentication. This specifies the authentication scheme
Serhiy Storchakaf47036c2013-12-24 11:04:36 +0200457and a 'realm'. The header looks like: ``WWW-Authenticate: SCHEME
Georg Brandl116aa622007-08-15 14:28:22 +0000458realm="REALM"``.
459
Georg Brandl48310cd2009-01-03 21:18:54 +0000460e.g. ::
Georg Brandl116aa622007-08-15 14:28:22 +0000461
Sandro Tosi08ccbf42012-04-24 17:36:41 +0200462 WWW-Authenticate: Basic realm="cPanel Users"
Georg Brandl116aa622007-08-15 14:28:22 +0000463
464
465The client should then retry the request with the appropriate name and password
466for the realm included as a header in the request. This is 'basic
467authentication'. In order to simplify this process we can create an instance of
468``HTTPBasicAuthHandler`` and an opener to use this handler.
469
470The ``HTTPBasicAuthHandler`` uses an object called a password manager to handle
471the mapping of URLs and realms to passwords and usernames. If you know what the
472realm is (from the authentication header sent by the server), then you can use a
473``HTTPPasswordMgr``. Frequently one doesn't care what the realm is. In that
474case, it is convenient to use ``HTTPPasswordMgrWithDefaultRealm``. This allows
475you to specify a default username and password for a URL. This will be supplied
476in the absence of you providing an alternative combination for a specific
477realm. We indicate this by providing ``None`` as the realm argument to the
478``add_password`` method.
479
480The top-level URL is the first URL that requires authentication. URLs "deeper"
481than the URL you pass to .add_password() will also match. ::
482
483 # create a password manager
Georg Brandl48310cd2009-01-03 21:18:54 +0000484 password_mgr = urllib.request.HTTPPasswordMgrWithDefaultRealm()
Georg Brandl116aa622007-08-15 14:28:22 +0000485
486 # Add the username and password.
Georg Brandl1f01deb2009-01-03 22:47:39 +0000487 # If we knew the realm, we could use it instead of None.
Georg Brandl116aa622007-08-15 14:28:22 +0000488 top_level_url = "http://example.com/foo/"
489 password_mgr.add_password(None, top_level_url, username, password)
490
Georg Brandl48310cd2009-01-03 21:18:54 +0000491 handler = urllib.request.HTTPBasicAuthHandler(password_mgr)
Georg Brandl116aa622007-08-15 14:28:22 +0000492
493 # create "opener" (OpenerDirector instance)
Georg Brandl48310cd2009-01-03 21:18:54 +0000494 opener = urllib.request.build_opener(handler)
Georg Brandl116aa622007-08-15 14:28:22 +0000495
496 # use the opener to fetch a URL
Georg Brandl48310cd2009-01-03 21:18:54 +0000497 opener.open(a_url)
Georg Brandl116aa622007-08-15 14:28:22 +0000498
499 # Install the opener.
Senthil Kumaranaca8fd72008-06-23 04:41:59 +0000500 # Now all calls to urllib.request.urlopen use our opener.
Georg Brandl48310cd2009-01-03 21:18:54 +0000501 urllib.request.install_opener(opener)
Georg Brandl116aa622007-08-15 14:28:22 +0000502
503.. note::
504
Ezio Melotti8e87fec2009-07-21 20:37:52 +0000505 In the above example we only supplied our ``HTTPBasicAuthHandler`` to
Georg Brandl116aa622007-08-15 14:28:22 +0000506 ``build_opener``. By default openers have the handlers for normal situations
R David Murray5aea37a2013-04-28 11:07:16 -0400507 -- ``ProxyHandler`` (if a proxy setting such as an :envvar:`http_proxy`
508 environment variable is set), ``UnknownHandler``, ``HTTPHandler``,
Georg Brandl116aa622007-08-15 14:28:22 +0000509 ``HTTPDefaultErrorHandler``, ``HTTPRedirectHandler``, ``FTPHandler``,
R David Murray5aea37a2013-04-28 11:07:16 -0400510 ``FileHandler``, ``DataHandler``, ``HTTPErrorProcessor``.
Georg Brandl116aa622007-08-15 14:28:22 +0000511
512``top_level_url`` is in fact *either* a full URL (including the 'http:' scheme
513component and the hostname and optionally the port number)
Serhiy Storchakad97b7dc2017-05-16 23:18:09 +0300514e.g. ``"http://example.com/"`` *or* an "authority" (i.e. the hostname,
515optionally including the port number) e.g. ``"example.com"`` or ``"example.com:8080"``
Georg Brandl116aa622007-08-15 14:28:22 +0000516(the latter example includes a port number). The authority, if present, must
Serhiy Storchakad97b7dc2017-05-16 23:18:09 +0300517NOT contain the "userinfo" component - for example ``"joe:password@example.com"`` is
Georg Brandl116aa622007-08-15 14:28:22 +0000518not correct.
519
520
521Proxies
522=======
523
Georg Brandl0f7ede42008-06-23 11:23:31 +0000524**urllib** will auto-detect your proxy settings and use those. This is through
R David Murray5aea37a2013-04-28 11:07:16 -0400525the ``ProxyHandler``, which is part of the normal handler chain when a proxy
R David Murray9330a942013-04-28 11:24:35 -0400526setting is detected. Normally that's a good thing, but there are occasions
527when it may not be helpful [#]_. One way to do this is to setup our own
528``ProxyHandler``, with no proxies defined. This is done using similar steps to
Serhiy Storchakaf47036c2013-12-24 11:04:36 +0200529setting up a `Basic Authentication`_ handler: ::
Georg Brandl116aa622007-08-15 14:28:22 +0000530
Senthil Kumaranaca8fd72008-06-23 04:41:59 +0000531 >>> proxy_support = urllib.request.ProxyHandler({})
532 >>> opener = urllib.request.build_opener(proxy_support)
533 >>> urllib.request.install_opener(opener)
Georg Brandl116aa622007-08-15 14:28:22 +0000534
535.. note::
536
Senthil Kumaranaca8fd72008-06-23 04:41:59 +0000537 Currently ``urllib.request`` *does not* support fetching of ``https`` locations
538 through a proxy. However, this can be enabled by extending urllib.request as
Georg Brandl116aa622007-08-15 14:28:22 +0000539 shown in the recipe [#]_.
540
Senthil Kumaran4cbb23f2016-07-30 23:24:16 -0700541.. note::
542
Senthil Kumaran17742f22016-07-30 23:39:06 -0700543 ``HTTP_PROXY`` will be ignored if a variable ``REQUEST_METHOD`` is set; see
544 the documentation on :func:`~urllib.request.getproxies`.
Senthil Kumaran4cbb23f2016-07-30 23:24:16 -0700545
Georg Brandl116aa622007-08-15 14:28:22 +0000546
547Sockets and Layers
548==================
549
Georg Brandl0f7ede42008-06-23 11:23:31 +0000550The Python support for fetching resources from the web is layered. urllib uses
551the :mod:`http.client` library, which in turn uses the socket library.
Georg Brandl116aa622007-08-15 14:28:22 +0000552
553As of Python 2.3 you can specify how long a socket should wait for a response
554before timing out. This can be useful in applications which have to fetch web
555pages. By default the socket module has *no timeout* and can hang. Currently,
Senthil Kumaranaca8fd72008-06-23 04:41:59 +0000556the socket timeout is not exposed at the http.client or urllib.request levels.
Georg Brandl24420152008-05-26 16:32:26 +0000557However, you can set the default timeout globally for all sockets using ::
Georg Brandl116aa622007-08-15 14:28:22 +0000558
559 import socket
Senthil Kumaranaca8fd72008-06-23 04:41:59 +0000560 import urllib.request
Georg Brandl116aa622007-08-15 14:28:22 +0000561
562 # timeout in seconds
563 timeout = 10
Georg Brandl48310cd2009-01-03 21:18:54 +0000564 socket.setdefaulttimeout(timeout)
Georg Brandl116aa622007-08-15 14:28:22 +0000565
Senthil Kumaranaca8fd72008-06-23 04:41:59 +0000566 # this call to urllib.request.urlopen now uses the default timeout
Georg Brandl116aa622007-08-15 14:28:22 +0000567 # we have set in the socket module
Senthil Kumaranaca8fd72008-06-23 04:41:59 +0000568 req = urllib.request.Request('http://www.voidspace.org.uk')
569 response = urllib.request.urlopen(req)
Georg Brandl116aa622007-08-15 14:28:22 +0000570
571
572-------
573
574
575Footnotes
576=========
577
578This document was reviewed and revised by John Lee.
579
Benjamin Peterson16ad5cf2015-09-20 23:17:41 +0500580.. [#] Google for example.
Martin Panter898573a2016-12-10 05:12:56 +0000581.. [#] Browser sniffing is a very bad practice for website design - building
Georg Brandl116aa622007-08-15 14:28:22 +0000582 sites using web standards is much more sensible. Unfortunately a lot of
583 sites still send different versions to different browsers.
584.. [#] The user agent for MSIE 6 is
585 *'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322)'*
586.. [#] For details of more HTTP request headers, see
587 `Quick Reference to HTTP Headers`_.
588.. [#] In my case I have to use a proxy to access the internet at work. If you
589 attempt to fetch *localhost* URLs through this proxy it blocks them. IE
Georg Brandl0f7ede42008-06-23 11:23:31 +0000590 is set to use the proxy, which urllib picks up on. In order to test
591 scripts with a localhost server, I have to prevent urllib from using
Georg Brandl116aa622007-08-15 14:28:22 +0000592 the proxy.
Georg Brandl48310cd2009-01-03 21:18:54 +0000593.. [#] urllib opener for SSL proxy (CONNECT method): `ASPN Cookbook Recipe
Serhiy Storchaka6dff0202016-05-07 10:49:07 +0300594 <https://code.activestate.com/recipes/456195/>`_.
Georg Brandl48310cd2009-01-03 21:18:54 +0000595