/Doc/library/urlparse.rst

http://unladen-swallow.googlecode.com/ · ReStructuredText · 314 lines · 229 code · 85 blank · 0 comment · 0 complexity · bba462c76fdfdbdcd68899d54feab190 MD5 · raw file

  1. :mod:`urlparse` --- Parse URLs into components
  2. ==============================================
  3. .. module:: urlparse
  4. :synopsis: Parse URLs into or assemble them from components.
  5. .. index::
  6. single: WWW
  7. single: World Wide Web
  8. single: URL
  9. pair: URL; parsing
  10. pair: relative; URL
  11. .. note::
  12. The :mod:`urlparse` module is renamed to :mod:`urllib.parse` in Python 3.0.
  13. The :term:`2to3` tool will automatically adapt imports when converting
  14. your sources to 3.0.
  15. This module defines a standard interface to break Uniform Resource Locator (URL)
  16. strings up in components (addressing scheme, network location, path etc.), to
  17. combine the components back into a URL string, and to convert a "relative URL"
  18. to an absolute URL given a "base URL."
  19. The module has been designed to match the Internet RFC on Relative Uniform
  20. Resource Locators (and discovered a bug in an earlier draft!). It supports the
  21. following URL schemes: ``file``, ``ftp``, ``gopher``, ``hdl``, ``http``,
  22. ``https``, ``imap``, ``mailto``, ``mms``, ``news``, ``nntp``, ``prospero``,
  23. ``rsync``, ``rtsp``, ``rtspu``, ``sftp``, ``shttp``, ``sip``, ``sips``,
  24. ``snews``, ``svn``, ``svn+ssh``, ``telnet``, ``wais``.
  25. .. versionadded:: 2.5
  26. Support for the ``sftp`` and ``sips`` schemes.
  27. The :mod:`urlparse` module defines the following functions:
  28. .. function:: urlparse(urlstring[, default_scheme[, allow_fragments]])
  29. Parse a URL into six components, returning a 6-tuple. This corresponds to the
  30. general structure of a URL: ``scheme://netloc/path;parameters?query#fragment``.
  31. Each tuple item is a string, possibly empty. The components are not broken up in
  32. smaller parts (for example, the network location is a single string), and %
  33. escapes are not expanded. The delimiters as shown above are not part of the
  34. result, except for a leading slash in the *path* component, which is retained if
  35. present. For example:
  36. >>> from urlparse import urlparse
  37. >>> o = urlparse('http://www.cwi.nl:80/%7Eguido/Python.html')
  38. >>> o # doctest: +NORMALIZE_WHITESPACE
  39. ParseResult(scheme='http', netloc='www.cwi.nl:80', path='/%7Eguido/Python.html',
  40. params='', query='', fragment='')
  41. >>> o.scheme
  42. 'http'
  43. >>> o.port
  44. 80
  45. >>> o.geturl()
  46. 'http://www.cwi.nl:80/%7Eguido/Python.html'
  47. If the *default_scheme* argument is specified, it gives the default addressing
  48. scheme, to be used only if the URL does not specify one. The default value for
  49. this argument is the empty string.
  50. If the *allow_fragments* argument is false, fragment identifiers are not
  51. allowed, even if the URL's addressing scheme normally does support them. The
  52. default value for this argument is :const:`True`.
  53. The return value is actually an instance of a subclass of :class:`tuple`. This
  54. class has the following additional read-only convenience attributes:
  55. +------------------+-------+--------------------------+----------------------+
  56. | Attribute | Index | Value | Value if not present |
  57. +==================+=======+==========================+======================+
  58. | :attr:`scheme` | 0 | URL scheme specifier | empty string |
  59. +------------------+-------+--------------------------+----------------------+
  60. | :attr:`netloc` | 1 | Network location part | empty string |
  61. +------------------+-------+--------------------------+----------------------+
  62. | :attr:`path` | 2 | Hierarchical path | empty string |
  63. +------------------+-------+--------------------------+----------------------+
  64. | :attr:`params` | 3 | Parameters for last path | empty string |
  65. | | | element | |
  66. +------------------+-------+--------------------------+----------------------+
  67. | :attr:`query` | 4 | Query component | empty string |
  68. +------------------+-------+--------------------------+----------------------+
  69. | :attr:`fragment` | 5 | Fragment identifier | empty string |
  70. +------------------+-------+--------------------------+----------------------+
  71. | :attr:`username` | | User name | :const:`None` |
  72. +------------------+-------+--------------------------+----------------------+
  73. | :attr:`password` | | Password | :const:`None` |
  74. +------------------+-------+--------------------------+----------------------+
  75. | :attr:`hostname` | | Host name (lower case) | :const:`None` |
  76. +------------------+-------+--------------------------+----------------------+
  77. | :attr:`port` | | Port number as integer, | :const:`None` |
  78. | | | if present | |
  79. +------------------+-------+--------------------------+----------------------+
  80. See section :ref:`urlparse-result-object` for more information on the result
  81. object.
  82. .. versionchanged:: 2.5
  83. Added attributes to return value.
  84. .. function:: parse_qs(qs[, keep_blank_values[, strict_parsing]])
  85. Parse a query string given as a string argument (data of type
  86. :mimetype:`application/x-www-form-urlencoded`). Data are returned as a
  87. dictionary. The dictionary keys are the unique query variable names and the
  88. values are lists of values for each name.
  89. The optional argument *keep_blank_values* is a flag indicating whether blank
  90. values in URL encoded queries should be treated as blank strings. A true value
  91. indicates that blanks should be retained as blank strings. The default false
  92. value indicates that blank values are to be ignored and treated as if they were
  93. not included.
  94. The optional argument *strict_parsing* is a flag indicating what to do with
  95. parsing errors. If false (the default), errors are silently ignored. If true,
  96. errors raise a :exc:`ValueError` exception.
  97. Use the :func:`urllib.urlencode` function to convert such dictionaries into
  98. query strings.
  99. .. function:: parse_qsl(qs[, keep_blank_values[, strict_parsing]])
  100. Parse a query string given as a string argument (data of type
  101. :mimetype:`application/x-www-form-urlencoded`). Data are returned as a list of
  102. name, value pairs.
  103. The optional argument *keep_blank_values* is a flag indicating whether blank
  104. values in URL encoded queries should be treated as blank strings. A true value
  105. indicates that blanks should be retained as blank strings. The default false
  106. value indicates that blank values are to be ignored and treated as if they were
  107. not included.
  108. The optional argument *strict_parsing* is a flag indicating what to do with
  109. parsing errors. If false (the default), errors are silently ignored. If true,
  110. errors raise a :exc:`ValueError` exception.
  111. Use the :func:`urllib.urlencode` function to convert such lists of pairs into
  112. query strings.
  113. .. function:: urlunparse(parts)
  114. Construct a URL from a tuple as returned by ``urlparse()``. The *parts* argument
  115. can be any six-item iterable. This may result in a slightly different, but
  116. equivalent URL, if the URL that was parsed originally had unnecessary delimiters
  117. (for example, a ? with an empty query; the RFC states that these are
  118. equivalent).
  119. .. function:: urlsplit(urlstring[, default_scheme[, allow_fragments]])
  120. This is similar to :func:`urlparse`, but does not split the params from the URL.
  121. This should generally be used instead of :func:`urlparse` if the more recent URL
  122. syntax allowing parameters to be applied to each segment of the *path* portion
  123. of the URL (see :rfc:`2396`) is wanted. A separate function is needed to
  124. separate the path segments and parameters. This function returns a 5-tuple:
  125. (addressing scheme, network location, path, query, fragment identifier).
  126. The return value is actually an instance of a subclass of :class:`tuple`. This
  127. class has the following additional read-only convenience attributes:
  128. +------------------+-------+-------------------------+----------------------+
  129. | Attribute | Index | Value | Value if not present |
  130. +==================+=======+=========================+======================+
  131. | :attr:`scheme` | 0 | URL scheme specifier | empty string |
  132. +------------------+-------+-------------------------+----------------------+
  133. | :attr:`netloc` | 1 | Network location part | empty string |
  134. +------------------+-------+-------------------------+----------------------+
  135. | :attr:`path` | 2 | Hierarchical path | empty string |
  136. +------------------+-------+-------------------------+----------------------+
  137. | :attr:`query` | 3 | Query component | empty string |
  138. +------------------+-------+-------------------------+----------------------+
  139. | :attr:`fragment` | 4 | Fragment identifier | empty string |
  140. +------------------+-------+-------------------------+----------------------+
  141. | :attr:`username` | | User name | :const:`None` |
  142. +------------------+-------+-------------------------+----------------------+
  143. | :attr:`password` | | Password | :const:`None` |
  144. +------------------+-------+-------------------------+----------------------+
  145. | :attr:`hostname` | | Host name (lower case) | :const:`None` |
  146. +------------------+-------+-------------------------+----------------------+
  147. | :attr:`port` | | Port number as integer, | :const:`None` |
  148. | | | if present | |
  149. +------------------+-------+-------------------------+----------------------+
  150. See section :ref:`urlparse-result-object` for more information on the result
  151. object.
  152. .. versionadded:: 2.2
  153. .. versionchanged:: 2.5
  154. Added attributes to return value.
  155. .. function:: urlunsplit(parts)
  156. Combine the elements of a tuple as returned by :func:`urlsplit` into a complete
  157. URL as a string. The *parts* argument can be any five-item iterable. This may
  158. result in a slightly different, but equivalent URL, if the URL that was parsed
  159. originally had unnecessary delimiters (for example, a ? with an empty query; the
  160. RFC states that these are equivalent).
  161. .. versionadded:: 2.2
  162. .. function:: urljoin(base, url[, allow_fragments])
  163. Construct a full ("absolute") URL by combining a "base URL" (*base*) with
  164. another URL (*url*). Informally, this uses components of the base URL, in
  165. particular the addressing scheme, the network location and (part of) the path,
  166. to provide missing components in the relative URL. For example:
  167. >>> from urlparse import urljoin
  168. >>> urljoin('http://www.cwi.nl/%7Eguido/Python.html', 'FAQ.html')
  169. 'http://www.cwi.nl/%7Eguido/FAQ.html'
  170. The *allow_fragments* argument has the same meaning and default as for
  171. :func:`urlparse`.
  172. .. note::
  173. If *url* is an absolute URL (that is, starting with ``//`` or ``scheme://``),
  174. the *url*'s host name and/or scheme will be present in the result. For example:
  175. .. doctest::
  176. >>> urljoin('http://www.cwi.nl/%7Eguido/Python.html',
  177. ... '//www.python.org/%7Eguido')
  178. 'http://www.python.org/%7Eguido'
  179. If you do not want that behavior, preprocess the *url* with :func:`urlsplit` and
  180. :func:`urlunsplit`, removing possible *scheme* and *netloc* parts.
  181. .. function:: urldefrag(url)
  182. If *url* contains a fragment identifier, returns a modified version of *url*
  183. with no fragment identifier, and the fragment identifier as a separate string.
  184. If there is no fragment identifier in *url*, returns *url* unmodified and an
  185. empty string.
  186. .. seealso::
  187. :rfc:`1738` - Uniform Resource Locators (URL)
  188. This specifies the formal syntax and semantics of absolute URLs.
  189. :rfc:`1808` - Relative Uniform Resource Locators
  190. This Request For Comments includes the rules for joining an absolute and a
  191. relative URL, including a fair number of "Abnormal Examples" which govern the
  192. treatment of border cases.
  193. :rfc:`2396` - Uniform Resource Identifiers (URI): Generic Syntax
  194. Document describing the generic syntactic requirements for both Uniform Resource
  195. Names (URNs) and Uniform Resource Locators (URLs).
  196. .. _urlparse-result-object:
  197. Results of :func:`urlparse` and :func:`urlsplit`
  198. ------------------------------------------------
  199. The result objects from the :func:`urlparse` and :func:`urlsplit` functions are
  200. subclasses of the :class:`tuple` type. These subclasses add the attributes
  201. described in those functions, as well as provide an additional method:
  202. .. method:: ParseResult.geturl()
  203. Return the re-combined version of the original URL as a string. This may differ
  204. from the original URL in that the scheme will always be normalized to lower case
  205. and empty components may be dropped. Specifically, empty parameters, queries,
  206. and fragment identifiers will be removed.
  207. The result of this method is a fixpoint if passed back through the original
  208. parsing function:
  209. >>> import urlparse
  210. >>> url = 'HTTP://www.Python.org/doc/#'
  211. >>> r1 = urlparse.urlsplit(url)
  212. >>> r1.geturl()
  213. 'http://www.Python.org/doc/'
  214. >>> r2 = urlparse.urlsplit(r1.geturl())
  215. >>> r2.geturl()
  216. 'http://www.Python.org/doc/'
  217. .. versionadded:: 2.5
  218. The following classes provide the implementations of the parse results:
  219. .. class:: BaseResult
  220. Base class for the concrete result classes. This provides most of the attribute
  221. definitions. It does not provide a :meth:`geturl` method. It is derived from
  222. :class:`tuple`, but does not override the :meth:`__init__` or :meth:`__new__`
  223. methods.
  224. .. class:: ParseResult(scheme, netloc, path, params, query, fragment)
  225. Concrete class for :func:`urlparse` results. The :meth:`__new__` method is
  226. overridden to support checking that the right number of arguments are passed.
  227. .. class:: SplitResult(scheme, netloc, path, query, fragment)
  228. Concrete class for :func:`urlsplit` results. The :meth:`__new__` method is
  229. overridden to support checking that the right number of arguments are passed.