blob: affa406b0c74b6168a6719bc871b9fecfb221d1c [file] [log] [blame]
Senthil Kumaranaca8fd72008-06-23 04:41:59 +00001:mod:`urllib.parse` --- Parse URLs into components
2==================================================
Georg Brandl116aa622007-08-15 14:28:22 +00003
Senthil Kumaranaca8fd72008-06-23 04:41:59 +00004.. module:: urllib.parse
Georg Brandl116aa622007-08-15 14:28:22 +00005 :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
Senthil Kumaranaca8fd72008-06-23 04:41:59 +000027The :mod:`urllib.parse` module defines the following functions:
Georg Brandl116aa622007-08-15 14:28:22 +000028
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
Senthil Kumaranaca8fd72008-06-23 04:41:59 +000040 >>> from urllib.parse import urlparse
Georg Brandl116aa622007-08-15 14:28:22 +000041 >>> 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
Senthil Kumaranaca8fd72008-06-23 04:41:59 +0000157 >>> from urllib.parse import urljoin
Georg Brandl116aa622007-08-15 14:28:22 +0000158 >>> 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
Senthil Kumaranaca8fd72008-06-23 04:41:59 +0000186.. function:: quote(string[, safe])
187
188 Replace special characters in *string* using the ``%xx`` escape. Letters,
189 digits, and the characters ``'_.-'`` are never quoted. The optional *safe*
190 parameter specifies additional characters that should not be quoted --- its
191 default value is ``'/'``.
192
193 Example: ``quote('/~connolly/')`` yields ``'/%7econnolly/'``.
194
195
196.. function:: quote_plus(string[, safe])
197
198 Like :func:`quote`, but also replaces spaces by plus signs, as required for
199 quoting HTML form values. Plus signs in the original string are escaped unless
200 they are included in *safe*. It also does not have *safe* default to ``'/'``.
201
202
203.. function:: unquote(string)
204
205 Replace ``%xx`` escapes by their single-character equivalent.
206
207 Example: ``unquote('/%7Econnolly/')`` yields ``'/~connolly/'``.
208
209
210.. function:: unquote_plus(string)
211
212 Like :func:`unquote`, but also replaces plus signs by spaces, as required for
213 unquoting HTML form values.
214
215
216.. function:: urlencode(query[, doseq])
217
218 Convert a mapping object or a sequence of two-element tuples to a "url-encoded"
219 string, suitable to pass to :func:`urlopen` above as the optional *data*
220 argument. This is useful to pass a dictionary of form fields to a ``POST``
221 request. The resulting string is a series of ``key=value`` pairs separated by
222 ``'&'`` characters, where both *key* and *value* are quoted using
223 :func:`quote_plus` above. If the optional parameter *doseq* is present and
224 evaluates to true, individual ``key=value`` pairs are generated for each element
225 of the sequence. When a sequence of two-element tuples is used as the *query*
226 argument, the first element of each tuple is a key and the second is a value.
227 The order of parameters in the encoded string will match the order of parameter
228 tuples in the sequence. The :mod:`cgi` module provides the functions
229 :func:`parse_qs` and :func:`parse_qsl` which are used to parse query strings
230 into Python data structures.
231
Georg Brandl116aa622007-08-15 14:28:22 +0000232
233.. seealso::
234
235 :rfc:`1738` - Uniform Resource Locators (URL)
236 This specifies the formal syntax and semantics of absolute URLs.
237
238 :rfc:`1808` - Relative Uniform Resource Locators
239 This Request For Comments includes the rules for joining an absolute and a
240 relative URL, including a fair number of "Abnormal Examples" which govern the
241 treatment of border cases.
242
243 :rfc:`2396` - Uniform Resource Identifiers (URI): Generic Syntax
244 Document describing the generic syntactic requirements for both Uniform Resource
245 Names (URNs) and Uniform Resource Locators (URLs).
246
247
248.. _urlparse-result-object:
249
250Results of :func:`urlparse` and :func:`urlsplit`
251------------------------------------------------
252
253The result objects from the :func:`urlparse` and :func:`urlsplit` functions are
254subclasses of the :class:`tuple` type. These subclasses add the attributes
255described in those functions, as well as provide an additional method:
256
257
258.. method:: ParseResult.geturl()
259
260 Return the re-combined version of the original URL as a string. This may differ
261 from the original URL in that the scheme will always be normalized to lower case
262 and empty components may be dropped. Specifically, empty parameters, queries,
263 and fragment identifiers will be removed.
264
265 The result of this method is a fixpoint if passed back through the original
Christian Heimesfe337bf2008-03-23 21:54:12 +0000266 parsing function:
Georg Brandl116aa622007-08-15 14:28:22 +0000267
Senthil Kumaranaca8fd72008-06-23 04:41:59 +0000268 >>> import urllib.parse
Georg Brandl116aa622007-08-15 14:28:22 +0000269 >>> url = 'HTTP://www.Python.org/doc/#'
270
Senthil Kumaranaca8fd72008-06-23 04:41:59 +0000271 >>> r1 = urllib.parse.urlsplit(url)
Georg Brandl116aa622007-08-15 14:28:22 +0000272 >>> r1.geturl()
273 'http://www.Python.org/doc/'
274
Senthil Kumaranaca8fd72008-06-23 04:41:59 +0000275 >>> r2 = urllib.parse.urlsplit(r1.geturl())
Georg Brandl116aa622007-08-15 14:28:22 +0000276 >>> r2.geturl()
277 'http://www.Python.org/doc/'
278
Georg Brandl116aa622007-08-15 14:28:22 +0000279
280The following classes provide the implementations of the parse results::
281
282
283.. class:: BaseResult
284
285 Base class for the concrete result classes. This provides most of the attribute
286 definitions. It does not provide a :meth:`geturl` method. It is derived from
287 :class:`tuple`, but does not override the :meth:`__init__` or :meth:`__new__`
288 methods.
289
290
291.. class:: ParseResult(scheme, netloc, path, params, query, fragment)
292
293 Concrete class for :func:`urlparse` results. The :meth:`__new__` method is
294 overridden to support checking that the right number of arguments are passed.
295
296
297.. class:: SplitResult(scheme, netloc, path, query, fragment)
298
299 Concrete class for :func:`urlsplit` results. The :meth:`__new__` method is
300 overridden to support checking that the right number of arguments are passed.
301