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