blob: 1f580230fb3276e0b6350c15701da248da044d32 [file] [log] [blame]
Georg Brandl8ec7f652007-08-15 14:28:01 +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
Brett Cannonf6afa332008-07-11 00:16:30 +000015.. 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.
19
20
Georg Brandl8ec7f652007-08-15 14:28:01 +000021This module defines a standard interface to break Uniform Resource Locator (URL)
22strings up in components (addressing scheme, network location, path etc.), to
23combine the components back into a URL string, and to convert a "relative URL"
24to an absolute URL given a "base URL."
25
26The module has been designed to match the Internet RFC on Relative Uniform
27Resource Locators (and discovered a bug in an earlier draft!). It supports the
28following 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``.
32
33.. versionadded:: 2.5
34 Support for the ``sftp`` and ``sips`` schemes.
35
36The :mod:`urlparse` module defines the following functions:
37
38
R. David Murray172e06e2010-05-25 15:32:06 +000039.. function:: urlparse(urlstring[, scheme[, allow_fragments]])
Georg Brandl8ec7f652007-08-15 14:28:01 +000040
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
Georg Brandle8f1b002008-03-22 22:04:10 +000047 present. For example:
Georg Brandl8ec7f652007-08-15 14:28:01 +000048
49 >>> from urlparse import urlparse
50 >>> o = urlparse('http://www.cwi.nl:80/%7Eguido/Python.html')
Georg Brandle8f1b002008-03-22 22:04:10 +000051 >>> o # doctest: +NORMALIZE_WHITESPACE
52 ParseResult(scheme='http', netloc='www.cwi.nl:80', path='/%7Eguido/Python.html',
53 params='', query='', fragment='')
Georg Brandl8ec7f652007-08-15 14:28:01 +000054 >>> o.scheme
55 'http'
56 >>> o.port
57 80
58 >>> o.geturl()
59 'http://www.cwi.nl:80/%7Eguido/Python.html'
60
R. David Murray172e06e2010-05-25 15:32:06 +000061 If the *scheme* argument is specified, it gives the default addressing
Georg Brandl8ec7f652007-08-15 14:28:01 +000062 scheme, to be used only if the URL does not specify one. The default value for
63 this argument is the empty string.
64
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`.
68
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:
71
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 +------------------+-------+--------------------------+----------------------+
97
98 See section :ref:`urlparse-result-object` for more information on the result
99 object.
100
101 .. versionchanged:: 2.5
102 Added attributes to return value.
103
Senthil Kumaran39824612010-04-22 12:10:13 +0000104 .. versionchanged:: 2.7
105 Added IPv6 URL parsing capabilities.
106
107
Facundo Batistac585df92008-09-03 22:35:50 +0000108.. function:: parse_qs(qs[, keep_blank_values[, strict_parsing]])
109
110 Parse a query string given as a string argument (data of type
111 :mimetype:`application/x-www-form-urlencoded`). Data are returned as a
112 dictionary. The dictionary keys are the unique query variable names and the
113 values are lists of values for each name.
114
115 The optional argument *keep_blank_values* is a flag indicating whether blank
116 values in URL encoded queries should be treated as blank strings. A true value
117 indicates that blanks should be retained as blank strings. The default false
118 value indicates that blank values are to be ignored and treated as if they were
119 not included.
120
121 The optional argument *strict_parsing* is a flag indicating what to do with
122 parsing errors. If false (the default), errors are silently ignored. If true,
123 errors raise a :exc:`ValueError` exception.
124
125 Use the :func:`urllib.urlencode` function to convert such dictionaries into
126 query strings.
127
Georg Brandla6714b22009-11-03 18:34:27 +0000128 .. versionadded:: 2.6
129 Copied from the :mod:`cgi` module.
130
Facundo Batistac585df92008-09-03 22:35:50 +0000131
132.. function:: parse_qsl(qs[, keep_blank_values[, strict_parsing]])
133
134 Parse a query string given as a string argument (data of type
135 :mimetype:`application/x-www-form-urlencoded`). Data are returned as a list of
136 name, value pairs.
137
138 The optional argument *keep_blank_values* is a flag indicating whether blank
139 values in URL encoded queries should be treated as blank strings. A true value
140 indicates that blanks should be retained as blank strings. The default false
141 value indicates that blank values are to be ignored and treated as if they were
142 not included.
143
144 The optional argument *strict_parsing* is a flag indicating what to do with
145 parsing errors. If false (the default), errors are silently ignored. If true,
146 errors raise a :exc:`ValueError` exception.
147
148 Use the :func:`urllib.urlencode` function to convert such lists of pairs into
149 query strings.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000150
Georg Brandla6714b22009-11-03 18:34:27 +0000151 .. versionadded:: 2.6
152 Copied from the :mod:`cgi` module.
153
154
Georg Brandl8ec7f652007-08-15 14:28:01 +0000155.. function:: urlunparse(parts)
156
157 Construct a URL from a tuple as returned by ``urlparse()``. The *parts* argument
158 can be any six-item iterable. This may result in a slightly different, but
159 equivalent URL, if the URL that was parsed originally had unnecessary delimiters
160 (for example, a ? with an empty query; the RFC states that these are
161 equivalent).
162
163
R. David Murray172e06e2010-05-25 15:32:06 +0000164.. function:: urlsplit(urlstring[, scheme[, allow_fragments]])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000165
166 This is similar to :func:`urlparse`, but does not split the params from the URL.
167 This should generally be used instead of :func:`urlparse` if the more recent URL
168 syntax allowing parameters to be applied to each segment of the *path* portion
169 of the URL (see :rfc:`2396`) is wanted. A separate function is needed to
170 separate the path segments and parameters. This function returns a 5-tuple:
171 (addressing scheme, network location, path, query, fragment identifier).
172
173 The return value is actually an instance of a subclass of :class:`tuple`. This
174 class has the following additional read-only convenience attributes:
175
176 +------------------+-------+-------------------------+----------------------+
177 | Attribute | Index | Value | Value if not present |
178 +==================+=======+=========================+======================+
179 | :attr:`scheme` | 0 | URL scheme specifier | empty string |
180 +------------------+-------+-------------------------+----------------------+
181 | :attr:`netloc` | 1 | Network location part | empty string |
182 +------------------+-------+-------------------------+----------------------+
183 | :attr:`path` | 2 | Hierarchical path | empty string |
184 +------------------+-------+-------------------------+----------------------+
185 | :attr:`query` | 3 | Query component | empty string |
186 +------------------+-------+-------------------------+----------------------+
187 | :attr:`fragment` | 4 | Fragment identifier | empty string |
188 +------------------+-------+-------------------------+----------------------+
189 | :attr:`username` | | User name | :const:`None` |
190 +------------------+-------+-------------------------+----------------------+
191 | :attr:`password` | | Password | :const:`None` |
192 +------------------+-------+-------------------------+----------------------+
193 | :attr:`hostname` | | Host name (lower case) | :const:`None` |
194 +------------------+-------+-------------------------+----------------------+
195 | :attr:`port` | | Port number as integer, | :const:`None` |
196 | | | if present | |
197 +------------------+-------+-------------------------+----------------------+
198
199 See section :ref:`urlparse-result-object` for more information on the result
200 object.
201
202 .. versionadded:: 2.2
203
204 .. versionchanged:: 2.5
205 Added attributes to return value.
206
207
208.. function:: urlunsplit(parts)
209
210 Combine the elements of a tuple as returned by :func:`urlsplit` into a complete
211 URL as a string. The *parts* argument can be any five-item iterable. This may
212 result in a slightly different, but equivalent URL, if the URL that was parsed
213 originally had unnecessary delimiters (for example, a ? with an empty query; the
214 RFC states that these are equivalent).
215
216 .. versionadded:: 2.2
217
218
219.. function:: urljoin(base, url[, allow_fragments])
220
221 Construct a full ("absolute") URL by combining a "base URL" (*base*) with
222 another URL (*url*). Informally, this uses components of the base URL, in
223 particular the addressing scheme, the network location and (part of) the path,
Georg Brandle8f1b002008-03-22 22:04:10 +0000224 to provide missing components in the relative URL. For example:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000225
226 >>> from urlparse import urljoin
227 >>> urljoin('http://www.cwi.nl/%7Eguido/Python.html', 'FAQ.html')
228 'http://www.cwi.nl/%7Eguido/FAQ.html'
229
230 The *allow_fragments* argument has the same meaning and default as for
231 :func:`urlparse`.
232
233 .. note::
234
235 If *url* is an absolute URL (that is, starting with ``//`` or ``scheme://``),
236 the *url*'s host name and/or scheme will be present in the result. For example:
237
Georg Brandle8f1b002008-03-22 22:04:10 +0000238 .. doctest::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000239
240 >>> urljoin('http://www.cwi.nl/%7Eguido/Python.html',
241 ... '//www.python.org/%7Eguido')
242 'http://www.python.org/%7Eguido'
243
244 If you do not want that behavior, preprocess the *url* with :func:`urlsplit` and
245 :func:`urlunsplit`, removing possible *scheme* and *netloc* parts.
246
247
248.. function:: urldefrag(url)
249
250 If *url* contains a fragment identifier, returns a modified version of *url*
251 with no fragment identifier, and the fragment identifier as a separate string.
252 If there is no fragment identifier in *url*, returns *url* unmodified and an
253 empty string.
254
255
256.. seealso::
257
Senthil Kumaran0a361812010-04-22 05:48:35 +0000258 :rfc:`3986` - Uniform Resource Identifiers
259 This is the current standard (STD66). Any changes to urlparse module
260 should conform to this. Certain deviations could be observed, which are
Senthil Kumaran39824612010-04-22 12:10:13 +0000261 mostly due backward compatiblity purposes and for certain de-facto
Senthil Kumaran0a361812010-04-22 05:48:35 +0000262 parsing requirements as commonly observed in major browsers.
263
264 :rfc:`2732` - Format for Literal IPv6 Addresses in URL's.
265 This specifies the parsing requirements of IPv6 URLs.
266
267 :rfc:`2396` - Uniform Resource Identifiers (URI): Generic Syntax
268 Document describing the generic syntactic requirements for both Uniform Resource
269 Names (URNs) and Uniform Resource Locators (URLs).
270
271 :rfc:`2368` - The mailto URL scheme.
272 Parsing requirements for mailto url schemes.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000273
274 :rfc:`1808` - Relative Uniform Resource Locators
275 This Request For Comments includes the rules for joining an absolute and a
276 relative URL, including a fair number of "Abnormal Examples" which govern the
277 treatment of border cases.
278
Senthil Kumaran0a361812010-04-22 05:48:35 +0000279 :rfc:`1738` - Uniform Resource Locators (URL)
280 This specifies the formal syntax and semantics of absolute URLs.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000281
282
283.. _urlparse-result-object:
284
285Results of :func:`urlparse` and :func:`urlsplit`
286------------------------------------------------
287
288The result objects from the :func:`urlparse` and :func:`urlsplit` functions are
289subclasses of the :class:`tuple` type. These subclasses add the attributes
290described in those functions, as well as provide an additional method:
291
292
293.. method:: ParseResult.geturl()
294
295 Return the re-combined version of the original URL as a string. This may differ
296 from the original URL in that the scheme will always be normalized to lower case
297 and empty components may be dropped. Specifically, empty parameters, queries,
298 and fragment identifiers will be removed.
299
300 The result of this method is a fixpoint if passed back through the original
Georg Brandle8f1b002008-03-22 22:04:10 +0000301 parsing function:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000302
303 >>> import urlparse
304 >>> url = 'HTTP://www.Python.org/doc/#'
305
306 >>> r1 = urlparse.urlsplit(url)
307 >>> r1.geturl()
308 'http://www.Python.org/doc/'
309
310 >>> r2 = urlparse.urlsplit(r1.geturl())
311 >>> r2.geturl()
312 'http://www.Python.org/doc/'
313
314 .. versionadded:: 2.5
315
Georg Brandlfc29f272009-01-02 20:25:14 +0000316The following classes provide the implementations of the parse results:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000317
318
319.. class:: BaseResult
320
321 Base class for the concrete result classes. This provides most of the attribute
322 definitions. It does not provide a :meth:`geturl` method. It is derived from
323 :class:`tuple`, but does not override the :meth:`__init__` or :meth:`__new__`
324 methods.
325
326
327.. class:: ParseResult(scheme, netloc, path, params, query, fragment)
328
329 Concrete class for :func:`urlparse` results. The :meth:`__new__` method is
330 overridden to support checking that the right number of arguments are passed.
331
332
333.. class:: SplitResult(scheme, netloc, path, query, fragment)
334
335 Concrete class for :func:`urlsplit` results. The :meth:`__new__` method is
336 overridden to support checking that the right number of arguments are passed.
337