blob: 4b86e88db92c7c3908f6198851217b32e7cb2ee1 [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001:mod:`urllib` --- Open arbitrary resources by URL
2=================================================
3
4.. module:: urllib
5 :synopsis: Open an arbitrary network resource by URL (requires sockets).
6
7
8.. index::
9 single: WWW
10 single: World Wide Web
11 single: URL
12
13This module provides a high-level interface for fetching data across the World
14Wide Web. In particular, the :func:`urlopen` function is similar to the
15built-in function :func:`open`, but accepts Universal Resource Locators (URLs)
16instead of filenames. Some restrictions apply --- it can only open URLs for
17reading, and no seek operations are available.
18
Christian Heimes790c8232008-01-07 21:14:23 +000019High-level interface
20--------------------
Georg Brandl116aa622007-08-15 14:28:22 +000021
22.. function:: urlopen(url[, data[, proxies]])
23
24 Open a network object denoted by a URL for reading. If the URL does not have a
25 scheme identifier, or if it has :file:`file:` as its scheme identifier, this
26 opens a local file (without universal newlines); otherwise it opens a socket to
27 a server somewhere on the network. If the connection cannot be made the
28 :exc:`IOError` exception is raised. If all went well, a file-like object is
29 returned. This supports the following methods: :meth:`read`, :meth:`readline`,
30 :meth:`readlines`, :meth:`fileno`, :meth:`close`, :meth:`info` and
Georg Brandl9afde1c2007-11-01 20:32:30 +000031 :meth:`geturl`. It also has proper support for the :term:`iterator` protocol. One
Georg Brandl116aa622007-08-15 14:28:22 +000032 caveat: the :meth:`read` method, if the size argument is omitted or negative,
33 may not read until the end of the data stream; there is no good way to determine
34 that the entire stream from a socket has been read in the general case.
35
36 Except for the :meth:`info` and :meth:`geturl` methods, these methods have the
37 same interface as for file objects --- see section :ref:`bltin-file-objects` in
38 this manual. (It is not a built-in file object, however, so it can't be used at
39 those few places where a true built-in file object is required.)
40
41 .. index:: module: mimetools
42
43 The :meth:`info` method returns an instance of the class
44 :class:`mimetools.Message` containing meta-information associated with the
45 URL. When the method is HTTP, these headers are those returned by the server
46 at the head of the retrieved HTML page (including Content-Length and
47 Content-Type). When the method is FTP, a Content-Length header will be
48 present if (as is now usual) the server passed back a file length in response
49 to the FTP retrieval request. A Content-Type header will be present if the
50 MIME type can be guessed. When the method is local-file, returned headers
51 will include a Date representing the file's last-modified time, a
52 Content-Length giving file size, and a Content-Type containing a guess at the
53 file's type. See also the description of the :mod:`mimetools` module.
54
55 The :meth:`geturl` method returns the real URL of the page. In some cases, the
56 HTTP server redirects a client to another URL. The :func:`urlopen` function
57 handles this transparently, but in some cases the caller needs to know which URL
58 the client was redirected to. The :meth:`geturl` method can be used to get at
59 this redirected URL.
60
61 If the *url* uses the :file:`http:` scheme identifier, the optional *data*
62 argument may be given to specify a ``POST`` request (normally the request type
63 is ``GET``). The *data* argument must be in standard
64 :mimetype:`application/x-www-form-urlencoded` format; see the :func:`urlencode`
65 function below.
66
67 The :func:`urlopen` function works transparently with proxies which do not
68 require authentication. In a Unix or Windows environment, set the
69 :envvar:`http_proxy`, or :envvar:`ftp_proxy` environment variables to a URL that
70 identifies the proxy server before starting the Python interpreter. For example
71 (the ``'%'`` is the command prompt)::
72
73 % http_proxy="http://www.someproxy.com:3128"
74 % export http_proxy
75 % python
76 ...
77
78 In a Windows environment, if no proxy environment variables are set, proxy
79 settings are obtained from the registry's Internet Settings section.
80
81 .. index:: single: Internet Config
82
83 In a Macintosh environment, :func:`urlopen` will retrieve proxy information from
84 Internet Config.
85
86 Alternatively, the optional *proxies* argument may be used to explicitly specify
87 proxies. It must be a dictionary mapping scheme names to proxy URLs, where an
88 empty dictionary causes no proxies to be used, and ``None`` (the default value)
89 causes environmental proxy settings to be used as discussed above. For
90 example::
91
92 # Use http://www.someproxy.com:3128 for http proxying
93 proxies = {'http': 'http://www.someproxy.com:3128'}
94 filehandle = urllib.urlopen(some_url, proxies=proxies)
95 # Don't use any proxies
96 filehandle = urllib.urlopen(some_url, proxies={})
97 # Use proxies from environment - both versions are equivalent
98 filehandle = urllib.urlopen(some_url, proxies=None)
99 filehandle = urllib.urlopen(some_url)
100
101 The :func:`urlopen` function does not support explicit proxy specification. If
102 you need to override environmental proxy settings, use :class:`URLopener`, or a
103 subclass such as :class:`FancyURLopener`.
104
105 Proxies which require authentication for use are not currently supported; this
106 is considered an implementation limitation.
107
Georg Brandl116aa622007-08-15 14:28:22 +0000108
109.. function:: urlretrieve(url[, filename[, reporthook[, data]]])
110
111 Copy a network object denoted by a URL to a local file, if necessary. If the URL
112 points to a local file, or a valid cached copy of the object exists, the object
113 is not copied. Return a tuple ``(filename, headers)`` where *filename* is the
114 local file name under which the object can be found, and *headers* is whatever
115 the :meth:`info` method of the object returned by :func:`urlopen` returned (for
116 a remote object, possibly cached). Exceptions are the same as for
117 :func:`urlopen`.
118
119 The second argument, if present, specifies the file location to copy to (if
120 absent, the location will be a tempfile with a generated name). The third
121 argument, if present, is a hook function that will be called once on
122 establishment of the network connection and once after each block read
123 thereafter. The hook will be passed three arguments; a count of blocks
124 transferred so far, a block size in bytes, and the total size of the file. The
125 third argument may be ``-1`` on older FTP servers which do not return a file
126 size in response to a retrieval request.
127
128 If the *url* uses the :file:`http:` scheme identifier, the optional *data*
129 argument may be given to specify a ``POST`` request (normally the request type
130 is ``GET``). The *data* argument must in standard
131 :mimetype:`application/x-www-form-urlencoded` format; see the :func:`urlencode`
132 function below.
133
Georg Brandl55ac8f02007-09-01 13:51:09 +0000134 :func:`urlretrieve` will raise :exc:`ContentTooShortError` when it detects that
135 the amount of data available was less than the expected amount (which is the
136 size reported by a *Content-Length* header). This can occur, for example, when
137 the download is interrupted.
Georg Brandl116aa622007-08-15 14:28:22 +0000138
Georg Brandl55ac8f02007-09-01 13:51:09 +0000139 The *Content-Length* is treated as a lower bound: if there's more data to read,
140 urlretrieve reads more data, but if less data is available, it raises the
141 exception.
Georg Brandl116aa622007-08-15 14:28:22 +0000142
Georg Brandl55ac8f02007-09-01 13:51:09 +0000143 You can still retrieve the downloaded data in this case, it is stored in the
144 :attr:`content` attribute of the exception instance.
Georg Brandl116aa622007-08-15 14:28:22 +0000145
Georg Brandl55ac8f02007-09-01 13:51:09 +0000146 If no *Content-Length* header was supplied, urlretrieve can not check the size
147 of the data it has downloaded, and just returns it. In this case you just have
148 to assume that the download was successful.
Georg Brandl116aa622007-08-15 14:28:22 +0000149
150
151.. data:: _urlopener
152
153 The public functions :func:`urlopen` and :func:`urlretrieve` create an instance
154 of the :class:`FancyURLopener` class and use it to perform their requested
155 actions. To override this functionality, programmers can create a subclass of
156 :class:`URLopener` or :class:`FancyURLopener`, then assign an instance of that
157 class to the ``urllib._urlopener`` variable before calling the desired function.
158 For example, applications may want to specify a different
159 :mailheader:`User-Agent` header than :class:`URLopener` defines. This can be
160 accomplished with the following code::
161
162 import urllib
163
164 class AppURLopener(urllib.FancyURLopener):
165 version = "App/1.7"
166
167 urllib._urlopener = AppURLopener()
168
169
170.. function:: urlcleanup()
171
172 Clear the cache that may have been built up by previous calls to
173 :func:`urlretrieve`.
174
175
Christian Heimes790c8232008-01-07 21:14:23 +0000176Utility functions
177-----------------
178
Georg Brandl116aa622007-08-15 14:28:22 +0000179.. function:: quote(string[, safe])
180
181 Replace special characters in *string* using the ``%xx`` escape. Letters,
182 digits, and the characters ``'_.-'`` are never quoted. The optional *safe*
183 parameter specifies additional characters that should not be quoted --- its
184 default value is ``'/'``.
185
186 Example: ``quote('/~connolly/')`` yields ``'/%7econnolly/'``.
187
188
189.. function:: quote_plus(string[, safe])
190
191 Like :func:`quote`, but also replaces spaces by plus signs, as required for
192 quoting HTML form values. Plus signs in the original string are escaped unless
193 they are included in *safe*. It also does not have *safe* default to ``'/'``.
194
195
196.. function:: unquote(string)
197
198 Replace ``%xx`` escapes by their single-character equivalent.
199
200 Example: ``unquote('/%7Econnolly/')`` yields ``'/~connolly/'``.
201
202
203.. function:: unquote_plus(string)
204
205 Like :func:`unquote`, but also replaces plus signs by spaces, as required for
206 unquoting HTML form values.
207
208
209.. function:: urlencode(query[, doseq])
210
211 Convert a mapping object or a sequence of two-element tuples to a "url-encoded"
212 string, suitable to pass to :func:`urlopen` above as the optional *data*
213 argument. This is useful to pass a dictionary of form fields to a ``POST``
214 request. The resulting string is a series of ``key=value`` pairs separated by
215 ``'&'`` characters, where both *key* and *value* are quoted using
216 :func:`quote_plus` above. If the optional parameter *doseq* is present and
217 evaluates to true, individual ``key=value`` pairs are generated for each element
218 of the sequence. When a sequence of two-element tuples is used as the *query*
219 argument, the first element of each tuple is a key and the second is a value.
220 The order of parameters in the encoded string will match the order of parameter
221 tuples in the sequence. The :mod:`cgi` module provides the functions
222 :func:`parse_qs` and :func:`parse_qsl` which are used to parse query strings
223 into Python data structures.
224
225
226.. function:: pathname2url(path)
227
228 Convert the pathname *path* from the local syntax for a path to the form used in
229 the path component of a URL. This does not produce a complete URL. The return
230 value will already be quoted using the :func:`quote` function.
231
232
233.. function:: url2pathname(path)
234
235 Convert the path component *path* from an encoded URL to the local syntax for a
236 path. This does not accept a complete URL. This function uses :func:`unquote`
237 to decode *path*.
238
239
Christian Heimes790c8232008-01-07 21:14:23 +0000240URL Opener objects
241------------------
242
Georg Brandl116aa622007-08-15 14:28:22 +0000243.. class:: URLopener([proxies[, **x509]])
244
245 Base class for opening and reading URLs. Unless you need to support opening
246 objects using schemes other than :file:`http:`, :file:`ftp:`, or :file:`file:`,
247 you probably want to use :class:`FancyURLopener`.
248
249 By default, the :class:`URLopener` class sends a :mailheader:`User-Agent` header
250 of ``urllib/VVV``, where *VVV* is the :mod:`urllib` version number.
251 Applications can define their own :mailheader:`User-Agent` header by subclassing
252 :class:`URLopener` or :class:`FancyURLopener` and setting the class attribute
253 :attr:`version` to an appropriate string value in the subclass definition.
254
255 The optional *proxies* parameter should be a dictionary mapping scheme names to
256 proxy URLs, where an empty dictionary turns proxies off completely. Its default
257 value is ``None``, in which case environmental proxy settings will be used if
258 present, as discussed in the definition of :func:`urlopen`, above.
259
260 Additional keyword parameters, collected in *x509*, may be used for
261 authentication of the client when using the :file:`https:` scheme. The keywords
262 *key_file* and *cert_file* are supported to provide an SSL key and certificate;
263 both are needed to support client authentication.
264
265 :class:`URLopener` objects will raise an :exc:`IOError` exception if the server
266 returns an error code.
267
Christian Heimes790c8232008-01-07 21:14:23 +0000268 .. method:: open(fullurl[, data])
269
270 Open *fullurl* using the appropriate protocol. This method sets up cache and
271 proxy information, then calls the appropriate open method with its input
272 arguments. If the scheme is not recognized, :meth:`open_unknown` is called.
273 The *data* argument has the same meaning as the *data* argument of
274 :func:`urlopen`.
275
276
277 .. method:: open_unknown(fullurl[, data])
278
279 Overridable interface to open unknown URL types.
280
281
282 .. method:: retrieve(url[, filename[, reporthook[, data]]])
283
284 Retrieves the contents of *url* and places it in *filename*. The return value
285 is a tuple consisting of a local filename and either a
286 :class:`mimetools.Message` object containing the response headers (for remote
287 URLs) or ``None`` (for local URLs). The caller must then open and read the
288 contents of *filename*. If *filename* is not given and the URL refers to a
289 local file, the input filename is returned. If the URL is non-local and
290 *filename* is not given, the filename is the output of :func:`tempfile.mktemp`
291 with a suffix that matches the suffix of the last path component of the input
292 URL. If *reporthook* is given, it must be a function accepting three numeric
293 parameters. It will be called after each chunk of data is read from the
294 network. *reporthook* is ignored for local URLs.
295
296 If the *url* uses the :file:`http:` scheme identifier, the optional *data*
297 argument may be given to specify a ``POST`` request (normally the request type
298 is ``GET``). The *data* argument must in standard
299 :mimetype:`application/x-www-form-urlencoded` format; see the :func:`urlencode`
300 function below.
301
302
303 .. attribute:: version
304
305 Variable that specifies the user agent of the opener object. To get
306 :mod:`urllib` to tell servers that it is a particular user agent, set this in a
307 subclass as a class variable or in the constructor before calling the base
308 constructor.
309
Georg Brandl116aa622007-08-15 14:28:22 +0000310
311.. class:: FancyURLopener(...)
312
313 :class:`FancyURLopener` subclasses :class:`URLopener` providing default handling
314 for the following HTTP response codes: 301, 302, 303, 307 and 401. For the 30x
315 response codes listed above, the :mailheader:`Location` header is used to fetch
316 the actual URL. For 401 response codes (authentication required), basic HTTP
317 authentication is performed. For the 30x response codes, recursion is bounded
318 by the value of the *maxtries* attribute, which defaults to 10.
319
320 For all other response codes, the method :meth:`http_error_default` is called
321 which you can override in subclasses to handle the error appropriately.
322
323 .. note::
324
325 According to the letter of :rfc:`2616`, 301 and 302 responses to POST requests
326 must not be automatically redirected without confirmation by the user. In
327 reality, browsers do allow automatic redirection of these responses, changing
328 the POST to a GET, and :mod:`urllib` reproduces this behaviour.
329
330 The parameters to the constructor are the same as those for :class:`URLopener`.
331
332 .. note::
333
334 When performing basic authentication, a :class:`FancyURLopener` instance calls
335 its :meth:`prompt_user_passwd` method. The default implementation asks the
336 users for the required information on the controlling terminal. A subclass may
337 override this method to support more appropriate behavior if needed.
338
Christian Heimes790c8232008-01-07 21:14:23 +0000339 The :class:`FancyURLopener` class offers one additional method that should be
340 overloaded to provide the appropriate behavior:
341
342 .. method:: prompt_user_passwd(host, realm)
343
344 Return information needed to authenticate the user at the given host in the
345 specified security realm. The return value should be a tuple, ``(user,
346 password)``, which can be used for basic authentication.
347
348 The implementation prompts for this information on the terminal; an application
349 should override this method to use an appropriate interaction model in the local
350 environment.
Georg Brandl116aa622007-08-15 14:28:22 +0000351
352.. exception:: ContentTooShortError(msg[, content])
353
354 This exception is raised when the :func:`urlretrieve` function detects that the
355 amount of the downloaded data is less than the expected amount (given by the
356 *Content-Length* header). The :attr:`content` attribute stores the downloaded
357 (and supposedly truncated) data.
358
Christian Heimes790c8232008-01-07 21:14:23 +0000359
360:mod:`urllib` Restrictions
361--------------------------
Georg Brandl116aa622007-08-15 14:28:22 +0000362
363 .. index::
364 pair: HTTP; protocol
365 pair: FTP; protocol
366
367* Currently, only the following protocols are supported: HTTP, (versions 0.9 and
368 1.0), FTP, and local files.
369
370* The caching feature of :func:`urlretrieve` has been disabled until I find the
371 time to hack proper processing of Expiration time headers.
372
373* There should be a function to query whether a particular URL is in the cache.
374
375* For backward compatibility, if a URL appears to point to a local file but the
376 file can't be opened, the URL is re-interpreted using the FTP protocol. This
377 can sometimes cause confusing error messages.
378
379* The :func:`urlopen` and :func:`urlretrieve` functions can cause arbitrarily
380 long delays while waiting for a network connection to be set up. This means
381 that it is difficult to build an interactive Web client using these functions
382 without using threads.
383
384 .. index::
385 single: HTML
386 pair: HTTP; protocol
387 module: htmllib
388
389* The data returned by :func:`urlopen` or :func:`urlretrieve` is the raw data
390 returned by the server. This may be binary data (such as an image), plain text
391 or (for example) HTML. The HTTP protocol provides type information in the reply
392 header, which can be inspected by looking at the :mailheader:`Content-Type`
393 header. If the returned data is HTML, you can use the module :mod:`htmllib` to
394 parse it.
395
396 .. index:: single: FTP
397
398* The code handling the FTP protocol cannot differentiate between a file and a
399 directory. This can lead to unexpected behavior when attempting to read a URL
400 that points to a file that is not accessible. If the URL ends in a ``/``, it is
401 assumed to refer to a directory and will be handled accordingly. But if an
402 attempt to read a file leads to a 550 error (meaning the URL cannot be found or
403 is not accessible, often for permission reasons), then the path is treated as a
404 directory in order to handle the case when a directory is specified by a URL but
405 the trailing ``/`` has been left off. This can cause misleading results when
406 you try to fetch a file whose read permissions make it inaccessible; the FTP
407 code will try to read it, fail with a 550 error, and then perform a directory
408 listing for the unreadable file. If fine-grained control is needed, consider
409 using the :mod:`ftplib` module, subclassing :class:`FancyURLOpener`, or changing
410 *_urlopener* to meet your needs.
411
412* This module does not support the use of proxies which require authentication.
413 This may be implemented in the future.
414
415 .. index:: module: urlparse
416
417* Although the :mod:`urllib` module contains (undocumented) routines to parse
418 and unparse URL strings, the recommended interface for URL manipulation is in
419 module :mod:`urlparse`.
420
421
Georg Brandl116aa622007-08-15 14:28:22 +0000422.. _urllib-examples:
423
424Examples
425--------
426
427Here is an example session that uses the ``GET`` method to retrieve a URL
428containing parameters::
429
430 >>> import urllib
431 >>> params = urllib.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0})
432 >>> f = urllib.urlopen("http://www.musi-cal.com/cgi-bin/query?%s" % params)
Collin Winterc79461b2007-09-01 23:34:30 +0000433 >>> print(f.read())
Georg Brandl116aa622007-08-15 14:28:22 +0000434
435The following example uses the ``POST`` method instead::
436
437 >>> import urllib
438 >>> params = urllib.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0})
439 >>> f = urllib.urlopen("http://www.musi-cal.com/cgi-bin/query", params)
Collin Winterc79461b2007-09-01 23:34:30 +0000440 >>> print(f.read())
Georg Brandl116aa622007-08-15 14:28:22 +0000441
442The following example uses an explicitly specified HTTP proxy, overriding
443environment settings::
444
445 >>> import urllib
446 >>> proxies = {'http': 'http://proxy.example.com:8080/'}
447 >>> opener = urllib.FancyURLopener(proxies)
448 >>> f = opener.open("http://www.python.org")
449 >>> f.read()
450
451The following example uses no proxies at all, overriding environment settings::
452
453 >>> import urllib
454 >>> opener = urllib.FancyURLopener({})
455 >>> f = opener.open("http://www.python.org/")
456 >>> f.read()
457