/Doc/library/urllib.rst

http://unladen-swallow.googlecode.com/ · ReStructuredText · 485 lines · 354 code · 131 blank · 0 comment · 0 complexity · 08357c6bdfa30054ae805cdbfab607ce MD5 · raw file

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