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