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