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