blob: 675cfd06591106ed1d3b35baac64a2b1c4e56d8a [file] [log] [blame]
Andrew M. Kuchling4b5caae2006-04-30 21:19:31 +00001==============================================
2 HOWTO Fetch Internet Resources Using urllib2
3==============================================
4------------------------------------------
5 Fetching URLs With Python
6------------------------------------------
7
8
9.. note::
10
11 There is an French translation of this HOWTO, available at `urllib2 - Le Manuel manquant <http://www.voidspace/python/urllib2_francais.shtml>`_.
12
13.. contents:: urllib2 Tutorial
14
15
16Introduction
17============
18
19.. sidebar:: Related Articles
20
21 You may also find useful the following articles on fetching web resources with Python :
22
23 * `Basic Authentication <http://www.voidspace.org.uk/python/articles/authentication.shtml>`_
24
25 A tutorial on *Basic Authentication*, with exampels in Python.
26
27 * `cookielib and ClientCookie <http://www.voidspace.org.uk/python/articles/cookielib.shtml>`_
28
29 How to handle cookies, when fetching web pages with Python.
30
31 This HOWTO is written by `Michael Foord <http://www.voidspace.org.uk/python/index.shtml>`_.
32
33**urllib2** is a Python_ module for fetching URLs (Uniform Resource Locators). It offers a very simple interface, in the form of the *urlopen* function. This is capable of fetching URLs using a variety of different protocols. It also offers a slightly more complex interface for handling common situations - like basic authentication, cookies, proxies, and so on. These are provided by objects called handlers and openers.
34
35For straightforward situations *urlopen* is very easy to use. But as soon as you encounter errors, or non-trivial cases, you will need some understanding of the HyperText Transfer Protocol. The most comprehensive reference to HTTP is :RFC:`2616`. This is a technical document and not intended to be easy to read. This HOWTO aims to illustrate using *urllib2*, with enough detail about HTTP to help you through. It is not intended to replace the `urllib2 docs`_ [#]_, but is supplementary to them.
36
37
38Fetching URLs
39=============
40
41HTTP is based on requests and responses - the client makes requests and servers send responses. Python mirrors this by having you form a ``Request`` object which represents the request you are making. In it's simplest form you create a Request object that specifies the URL you want to fetch [#]_. Calling ``urlopen`` with this Request object returns a handle on the page requested. This handle is a file like object : ::
42
43 import urllib2
44
45 the_url = 'http://www.voidspace.org.uk'
46 req = urllib2.Request(the_url)
47 handle = urllib2.urlopen(req)
48 the_page = handle.read()
49
50There are two extra things that Request objects allow you to do. Sometimes you want to **POST** data to a CGI (Common Gateway Interface) [#]_ or other web application. This is what your browser does when you fill in a FORM on the web. You may be mimicking a FORM submission, or transmitting data to your own application. In either case the data needs to be encoded for safe transmission over HTTP, and then passed to the Request object as the ``data`` argument. The encoding is done using a function from the ``urllib`` library *not* from ``urllib2``. ::
51
52 import urllib
53 import urllib2
54
55 the_url = 'http://www.someserver.com/cgi-bin/register.cgi'
56 values = {'name' : 'Michael Foord',
57 'location' : 'Northampton',
58 'language' : 'Python' }
59
60 data = urllib.urlencode(values)
61 req = urllib2.Request(the_url, data)
62 handle = urllib2.urlopen(req)
63 the_page = handle.read()
64
65Some websites [#]_ dislike being browsed by programs, or send different versions to different browsers [#]_ . By default urllib2 identifies itself as ``Python-urllib/2.4``, which may confuse the site, or just plain not work. The way a browser identifies itself is through the ``User-Agent`` header [#]_. When you create a Request object you can pass a dictionary of headers in. The following example makes the same request as above, but identifies itself as a version of Internet Explorer [#]_. ::
66
67 import urllib
68 import urllib2
69
70 the_url = 'http://www.someserver.com/cgi-bin/register.cgi'
71 user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
72 values = {'name' : 'Michael Foord',
73 'location' : 'Northampton',
74 'language' : 'Python' }
75 headers = { 'User-Agent' : user_agent }
76
77 data = urllib.urlencode(values)
78 req = urllib2.Request(the_url, data, headers)
79 handle = urllib2.urlopen(req)
80 the_page = handle.read()
81
82The handle also has two useful methods. See the section on `info and geturl`_ which comes after we have a look at what happens when things go wrong.
83
84
85Coping With Errors
86==================
87
88*urlopen* raises ``URLError`` or ``HTTPError`` in the event of an error. ``HTTPError`` is a subclass of ``URLError``, which is a subclass of ``IOError``. This means you can trap for ``IOError`` if you want. ::
89
90 req = urllib2.Request(some_url)
91 try:
92 handle = urllib2.urlopen(req)
93 except IOError:
94 print 'Something went wrong'
95 else:
96 print handle.read()
97
98URLError
99--------
100
101If the request fails to reach a server then urlopen will raise a ``URLError``. This will usually be because there is no network connection (no route to the specified server), or the specified server doesn't exist.
102
103In this case, the exception raised will have a 'reason' attribute, which is a tuple containing an error code and a text error message.
104
105e.g. ::
106
107 >>> req = urllib2.Request('http://www.pretend_server.org')
108 >>> try: urllib2.urlopen(req)
109 >>> except IOError, e:
110 >>> print e.reason
111 >>>
112 (4, 'getaddrinfo failed')
113
114
115HTTPError
116---------
117
118If the request reaches a server, but the server is unable to fulfil the request, it returns an error code. The default handlers will hande some of these errors for you. For those it can't handle, urlopen will raise an ``HTTPError``. Typical errors include '404' (page not found), '403' (request forbidden), and '401' (authentication required).
119
120See http://www.w3.org/Protocols/HTTP/HTRESP.html for a reference on all the http error codes.
121
122The ``HTTPError`` instance raised will have an integer 'code' attribute, which corresponds to the error sent by the server.
123
124There is a useful dictionary of response codes in ``HTTPBaseServer``, that shows all the defined response codes. Because the default handlers handle redirects (codes in the 300 range), and codes in the 100-299 range indicate success, you will usually only see error codes in the 400-599 range.
125
126Error Codes
127~~~~~~~~~~~
128
129.. note::
130
131 As of Python 2.5 a dictionary like this one has become part of ``urllib2``.
132
133::
134
135 # Table mapping response codes to messages; entries have the
136 # form {code: (shortmessage, longmessage)}.
137 httpresponses = {
138 100: ('Continue', 'Request received, please continue'),
139 101: ('Switching Protocols',
140 'Switching to new protocol; obey Upgrade header'),
141
142 200: ('OK', 'Request fulfilled, document follows'),
143 201: ('Created', 'Document created, URL follows'),
144 202: ('Accepted',
145 'Request accepted, processing continues off-line'),
146 203: ('Non-Authoritative Information',
147 'Request fulfilled from cache'),
148 204: ('No response', 'Request fulfilled, nothing follows'),
149 205: ('Reset Content', 'Clear input form for further input.'),
150 206: ('Partial Content', 'Partial content follows.'),
151
152 300: ('Multiple Choices',
153 'Object has several resources -- see URI list'),
154 301: ('Moved Permanently',
155 'Object moved permanently -- see URI list'),
156 302: ('Found', 'Object moved temporarily -- see URI list'),
157 303: ('See Other', 'Object moved -- see Method and URL list'),
158 304: ('Not modified',
159 'Document has not changed since given time'),
160 305: ('Use Proxy',
161 'You must use proxy specified in Location'
162 ' to access this resource.'),
163 307: ('Temporary Redirect',
164 'Object moved temporarily -- see URI list'),
165
166 400: ('Bad request',
167 'Bad request syntax or unsupported method'),
168 401: ('Unauthorized',
169 'No permission -- see authorization schemes'),
170 402: ('Payment required',
171 'No payment -- see charging schemes'),
172 403: ('Forbidden',
173 'Request forbidden -- authorization will not help'),
174 404: ('Not Found', 'Nothing matches the given URI'),
175 405: ('Method Not Allowed',
176 'Specified method is invalid for this server.'),
177 406: ('Not Acceptable',
178 'URI not available in preferred format.'),
179 407: ('Proxy Authentication Required',
180 'You must authenticate with '
181 'this proxy before proceeding.'),
182 408: ('Request Time-out',
183 'Request timed out; try again later.'),
184 409: ('Conflict', 'Request conflict.'),
185 410: ('Gone',
186 'URI no longer exists and has been permanently removed.'),
187 411: ('Length Required', 'Client must specify Content-Length.'),
188 412: ('Precondition Failed',
189 'Precondition in headers is false.'),
190 413: ('Request Entity Too Large', 'Entity is too large.'),
191 414: ('Request-URI Too Long', 'URI is too long.'),
192 415: ('Unsupported Media Type',
193 'Entity body in unsupported format.'),
194 416: ('Requested Range Not Satisfiable',
195 'Cannot satisfy request range.'),
196 417: ('Expectation Failed',
197 'Expect condition could not be satisfied.'),
198
199 500: ('Internal error', 'Server got itself in trouble'),
200 501: ('Not Implemented',
201 'Server does not support this operation'),
202 502: ('Bad Gateway',
203 'Invalid responses from another server/proxy.'),
204 503: ('Service temporarily overloaded',
205 'The server cannot '
206 'process the request due to a high load'),
207 504: ('Gateway timeout',
208 'The gateway server did not receive a timely response'),
209 505: ('HTTP Version not supported', 'Cannot fulfill request.'),
210 }
211
212When an error is raised the server responds by returning an http error code *and* an error page. You can use the ``HTTPError`` instance as a handle on the page returned. This means that as well as the code attribute, it also has read, geturl, and info, methods. ::
213
214 >>> req = urllib2.Request('http://www.python.org/fish.html')
215 >>> try:
216 >>> urllib2.urlopen(req)
217 >>> except IOError, e:
218 >>> print e.code
219 >>> print e.read()
220 >>>
221 404
222 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
223 "http://www.w3.org/TR/html4/loose.dtd">
224 <?xml-stylesheet href="./css/ht2html.css"
225 type="text/css"?>
226 <html><head><title>Error 404: File Not Found</title>
227 ...... etc...
228
229Wrapping it Up
230--------------
231
232So if you want to be prepared for ``HTTPError`` *or* ``URLError`` there are two
233basic approaches. I prefer the second approach.
234
235Number 1
236~~~~~~~~
237
238::
239
240
241 from urllib2 import Request, urlopen, URLError, HTTPError
242 req = Request(someurl)
243 try:
244 handle = urlopen(req)
245 except HTTPError, e:
246 print 'The server couldn\'t fulfill the request.'
247 print 'Error code: ', e.code
248 except URLError, e:
249 print 'We failed to reach a server.'
250 print 'Reason: ', e.reason
251 else:
252 # everything is fine
253
254
255.. note::
256
257 The ``except HTTPError`` *must* come first, otherwise ``except URLError`` will *also* catch an ``HTTPError``.
258
259Number 2
260~~~~~~~~
261
262::
263
264 from urllib2 import Request, urlopen
265 req = Request(someurl)
266 try:
267 handle = urlopen(req)
268 except IOError, e:
269 if hasattr(e, 'reason'):
270 print 'We failed to reach a server.'
271 print 'Reason: ', e.reason
272 elif hasattr(e, 'code'):
273 print 'The server couldn\'t fulfill the request.'
274 print 'Error code: ', e.code
275 else:
276 # everything is fine
277
278
279info and geturl
280===============
281
282The handle returned by urlopen (or the ``HTTPError`` instance) has two useful methods ``info`` and ``geturl``.
283
284**geturl** - this returns the real url of the page fetched. This is useful because ``urlopen`` (or the openener object used) may have followed a redirect. The url of the page fetched may not be the same as the url requested.
285
286**info** - this returns a dictionary like object that describes the page fetched, particularly the headers sent by the server. It is actually an ``httplib.HTTPMessage`` instance. In versions of Python prior to 2.3.4 it wasn't safe to iterate over the object directly, so you should iterate over the list returned by ``msg.keys()`` instead.
287
288Typical headers include 'content-length', 'content-type', and so on. See the `Quick Reference to HTTP Headers`_ for a useful reference on the different sort of headers.
289
290
291Openers and Handlers
292====================
293
294Openers and handlers are slightly esoteric parts of **urllib2**. When you fetch a URL you use an opener. Normally we have been using the default opener - via ``urlopen`` - but you can create custom openers. Openers use handlers.
295
296``build_opener`` is used to create ``opener`` objects - for fetching URLs with specific handlers installed. Handlers can handle cookies, authentication, and other common but slightly specialised situations. Opener objects have an ``open`` method, which can be called directly to fetch urls in the same way as the ``urlopen`` function.
297
298``install_opener`` can be used to make an ``opener`` object the default opener. This means that calls to ``urlopen`` will use the opener you have installed.
299
300
301Basic Authentication
302====================
303
304To illustrate creating and installing a handler we will use the ``HTTPBasicAuthHandler``. For a more detailed discussion of this subject - including an explanation of how Basic Authentication works - see the `Basic Authentication Tutorial`_.
305
306When authentication is required, the server sends a header (as well as the 401 error code) requesting authentication. This specifies the authentication scheme and a 'realm'. The header looks like : ``www-authenticate: SCHEME realm="REALM"``.
307
308e.g. ::
309
310 www-authenticate: Basic realm="cPanel"
311
312
313The client should then retry the request with the appropriate name and password for the realm included as a header in the request. This is 'basic authentication'. In order to simplify this process we can create an instance of ``HTTPBasicAuthHandler`` and an opener to use this handler.
314
315The ``HTTPBasicAuthHandler`` uses an object called a password manager to handle the mapping of URIs and realms to passwords and usernames. If you know what the realm is (from the authentication header sent by the server), then you can use a ``HTTPPasswordMgr``. Generally there is only one realm per URI, so it is possible to use ``HTTPPasswordMgrWithDefaultRealm``. This allows you to specify a default username and password for a URI. This will be supplied in the absence of yoou providing an alternative combination for a specific realm. We signify this by providing ``None`` as the realm argument to the ``add_password`` method.
316
317The toplevelurl is the first url that requires authentication. This is usually a 'super-url' of any others in the same realm. ::
318
319 password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
320 # create a password manager
321
322 password_mgr.add_password(None,
323 top_level_url, username, password)
324 # add the username and password
325 # if we knew the realm, we could
326 # use it instead of ``None``
327
328 handler = urllib2.HTTPBasicAuthHandler(password_mgr)
329 # create the handler
330
331 opener = urllib2.build_opener(handler)
332 # from handler to opener
333
334 opener.open(a_url)
335 # use the opener to fetch a URL
336
337 urllib2.install_opener(opener)
338 # install the opener
339 # now all calls to urllib2.urlopen use our opener
340
341.. note::
342
343 In the above example we only supplied our ``HHTPBasicAuthHandler`` to ``build_opener``. By default openers have the handlers for normal situations - ``ProxyHandler``, ``UnknownHandler``, ``HTTPHandler``, ``HTTPDefaultErrorHandler``, ``HTTPRedirectHandler``, ``FTPHandler``, ``FileHandler``, ``HTTPErrorProcessor``. The only reason to explicitly supply these to ``build_opener`` (which chains handlers provided as a list), would be to change the order they appear in the chain.
344
345One thing not to get bitten by is that the ``top_level_url`` in the code above *must not* contain the protocol - the ``http://`` part. So if the URL we are trying to access is ``http://www.someserver.com/path/page.html``, then we set : ::
346
347 top_level_url = "www.someserver.com/path/page.html"
348 # *no* http:// !!
349
350It took me a long time to track that down the first time I tried to use handlers.
351
352
353Proxies
354=======
355
356**urllib2** will auto-detect your proxy settings and use those. This is through the ``ProxyHandler`` which is part of the normal handler chain. Normally that's a good thing, but there are occasions when it may not be helpful [#]_. In order to do this we need to setup our own ``ProxyHandler``, with no proxies defined. This is done using similar steps to setting up a `Basic Authentication`_ handler : ::
357
358 >>> proxy_support = urllib2.ProxyHandler({})
359 >>> opener = urllib2.build_opener(proxy_support)
360 >>> urllib2.install_opener(opener)
361
362.. caution::
363
364 Currently ``urllib2`` *does not* support fetching of ``https`` locations through
365 a proxy. This can be a problem.
366
367Sockets and Layers
368==================
369
370The Python support for fetching resources from the web is layered. urllib2 uses the httplib library, which in turn uses the socket library.
371
372As of Python 2.3 you can specify how long a socket should wait for a response before timing out. This can be useful in applications which have to fetch web pages. By default the socket module has *no timeout* and can hang. To set the timeout use : ::
373
374 import socket
375 import urllib2
376
377 timeout = 10
378 # timeout in seconds
379 socket.setdefaulttimeout(timeout)
380
381 req = urllib2.Request('http://www.voidspace.org.uk')
382 handle = urllib2.urlopen(req)
383 # this call to urllib2.urlopen
384 # now uses the default timeout
385 # we have set in the socket module
386
387
388-------
389
390
391Footnotes
392===========
393
394.. [#] Possibly some of this tutorial will make it into the standard library docs for versions of Python after 2.4.1.
395.. [#] You *can* fetch URLs directly with urlopen, without using a request object. It's more explicit, and therefore more Pythonic, to use ``urllib2.Request`` though. It also makes it easier to add headers to your request.
396.. [#] For an introduction to the CGI protocol see `Writing Web Applications in Python`_.
397.. [#] Like Google for example. The *proper* way to use google from a program is to use PyGoogle_ of course. See `Voidspace Google`_ for some examples of using the Google API.
398.. [#] Browser sniffing is a very bad practise for website design - building sites using web standards is much more sensible. Unfortunately a lot of sites still send different versions to different browsers.
399.. [#] The user agent for MSIE 6 is *'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322)'*
400.. [#] For details of more HTTP request headers, see `Quick Reference to HTTP Headers`_.
401
402.. [#] In my case I have to use a proxy to access the internet at work. If you attempt to fetch *localhost* URLs through this proxy it blocks them. IE is set to use the proxy, which urllib2 picks up on. In order to test scripts with a localhost server, I have to prevent urllib2 from using the proxy.
403
404.. _Python: http://www.python.org
405.. _urllib2 docs: http://docs.python.org/lib/module-urllib2.html
406.. _Quick Reference to HTTP Headers: http://www.cs.tut.fi/~jkorpela/http.html
407.. _PyGoogle: http://pygoogle.sourceforge.net
408.. _Voidspace Google: http://www.voidspace.org.uk/python/recipebook.shtml#google
409.. _Writing Web Applications in Python: http://www.pyzine.com/Issue008/Section_Articles/article_CGIOne.html
410.. _Basic Authentication Tutorial: http://www.voidspace.org.uk/python/articles/authentication.shtml