Senthil Kumaran | aca8fd7 | 2008-06-23 04:41:59 +0000 | [diff] [blame] | 1 | :mod:`urllib.parse` --- Parse URLs into components |
| 2 | ================================================== |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 3 | |
Senthil Kumaran | aca8fd7 | 2008-06-23 04:41:59 +0000 | [diff] [blame] | 4 | .. module:: urllib.parse |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 5 | :synopsis: Parse URLs into or assemble them from components. |
| 6 | |
Terry Jan Reedy | fa089b9 | 2016-06-11 15:02:54 -0400 | [diff] [blame] | 7 | **Source code:** :source:`Lib/urllib/parse.py` |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 8 | |
| 9 | .. index:: |
| 10 | single: WWW |
| 11 | single: World Wide Web |
| 12 | single: URL |
| 13 | pair: URL; parsing |
| 14 | pair: relative; URL |
| 15 | |
Éric Araujo | 19f9b71 | 2011-08-19 00:49:18 +0200 | [diff] [blame] | 16 | -------------- |
| 17 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 18 | This module defines a standard interface to break Uniform Resource Locator (URL) |
| 19 | strings up in components (addressing scheme, network location, path etc.), to |
| 20 | combine the components back into a URL string, and to convert a "relative URL" |
| 21 | to an absolute URL given a "base URL." |
| 22 | |
| 23 | The module has been designed to match the Internet RFC on Relative Uniform |
Senthil Kumaran | 4a27d9f | 2012-06-28 21:07:58 -0700 | [diff] [blame] | 24 | Resource Locators. It supports the following URL schemes: ``file``, ``ftp``, |
| 25 | ``gopher``, ``hdl``, ``http``, ``https``, ``imap``, ``mailto``, ``mms``, |
| 26 | ``news``, ``nntp``, ``prospero``, ``rsync``, ``rtsp``, ``rtspu``, ``sftp``, |
| 27 | ``shttp``, ``sip``, ``sips``, ``snews``, ``svn``, ``svn+ssh``, ``telnet``, |
Berker Peksag | f676748 | 2016-09-16 14:43:58 +0300 | [diff] [blame] | 28 | ``wais``, ``ws``, ``wss``. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 29 | |
Nick Coghlan | 9fc443c | 2010-11-30 15:48:08 +0000 | [diff] [blame] | 30 | The :mod:`urllib.parse` module defines functions that fall into two broad |
| 31 | categories: URL parsing and URL quoting. These are covered in detail in |
| 32 | the following sections. |
| 33 | |
| 34 | URL Parsing |
| 35 | ----------- |
| 36 | |
| 37 | The URL parsing functions focus on splitting a URL string into its components, |
| 38 | or on combining URL components into a URL string. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 39 | |
R. David Murray | f5077aa | 2010-05-25 15:36:46 +0000 | [diff] [blame] | 40 | .. function:: urlparse(urlstring, scheme='', allow_fragments=True) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 41 | |
| 42 | Parse a URL into six components, returning a 6-tuple. This corresponds to the |
| 43 | general structure of a URL: ``scheme://netloc/path;parameters?query#fragment``. |
| 44 | Each tuple item is a string, possibly empty. The components are not broken up in |
| 45 | smaller parts (for example, the network location is a single string), and % |
| 46 | escapes are not expanded. The delimiters as shown above are not part of the |
| 47 | result, except for a leading slash in the *path* component, which is retained if |
Christian Heimes | fe337bf | 2008-03-23 21:54:12 +0000 | [diff] [blame] | 48 | present. For example: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 49 | |
Senthil Kumaran | aca8fd7 | 2008-06-23 04:41:59 +0000 | [diff] [blame] | 50 | >>> from urllib.parse import urlparse |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 51 | >>> o = urlparse('http://www.cwi.nl:80/%7Eguido/Python.html') |
Christian Heimes | fe337bf | 2008-03-23 21:54:12 +0000 | [diff] [blame] | 52 | >>> o # doctest: +NORMALIZE_WHITESPACE |
| 53 | ParseResult(scheme='http', netloc='www.cwi.nl:80', path='/%7Eguido/Python.html', |
| 54 | params='', query='', fragment='') |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 55 | >>> o.scheme |
| 56 | 'http' |
| 57 | >>> o.port |
| 58 | 80 |
| 59 | >>> o.geturl() |
| 60 | 'http://www.cwi.nl:80/%7Eguido/Python.html' |
| 61 | |
Senthil Kumaran | 7089a4e | 2010-11-07 12:57:04 +0000 | [diff] [blame] | 62 | Following the syntax specifications in :rfc:`1808`, urlparse recognizes |
| 63 | a netloc only if it is properly introduced by '//'. Otherwise the |
| 64 | input is presumed to be a relative URL and thus to start with |
| 65 | a path component. |
Senthil Kumaran | 84c7d9f | 2010-08-04 04:50:44 +0000 | [diff] [blame] | 66 | |
Marco Buttu | e65fcde | 2017-04-27 14:23:34 +0200 | [diff] [blame] | 67 | .. doctest:: |
| 68 | :options: +NORMALIZE_WHITESPACE |
| 69 | |
Senthil Kumaran | fe9230a | 2011-06-19 13:52:49 -0700 | [diff] [blame] | 70 | >>> from urllib.parse import urlparse |
Senthil Kumaran | 84c7d9f | 2010-08-04 04:50:44 +0000 | [diff] [blame] | 71 | >>> urlparse('//www.cwi.nl:80/%7Eguido/Python.html') |
| 72 | ParseResult(scheme='', netloc='www.cwi.nl:80', path='/%7Eguido/Python.html', |
| 73 | params='', query='', fragment='') |
Senthil Kumaran | 8fd3669 | 2013-02-26 01:02:58 -0800 | [diff] [blame] | 74 | >>> urlparse('www.cwi.nl/%7Eguido/Python.html') |
Senthil Kumaran | 21b2933 | 2013-09-30 22:12:16 -0700 | [diff] [blame] | 75 | ParseResult(scheme='', netloc='', path='www.cwi.nl/%7Eguido/Python.html', |
Senthil Kumaran | 84c7d9f | 2010-08-04 04:50:44 +0000 | [diff] [blame] | 76 | params='', query='', fragment='') |
| 77 | >>> urlparse('help/Python.html') |
| 78 | ParseResult(scheme='', netloc='', path='help/Python.html', params='', |
| 79 | query='', fragment='') |
| 80 | |
Berker Peksag | 89584c9 | 2015-06-25 23:38:48 +0300 | [diff] [blame] | 81 | The *scheme* argument gives the default addressing scheme, to be |
| 82 | used only if the URL does not specify one. It should be the same type |
| 83 | (text or bytes) as *urlstring*, except that the default value ``''`` is |
| 84 | always allowed, and is automatically converted to ``b''`` if appropriate. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 85 | |
| 86 | If the *allow_fragments* argument is false, fragment identifiers are not |
Berker Peksag | 89584c9 | 2015-06-25 23:38:48 +0300 | [diff] [blame] | 87 | recognized. Instead, they are parsed as part of the path, parameters |
| 88 | or query component, and :attr:`fragment` is set to the empty string in |
| 89 | the return value. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 90 | |
| 91 | The return value is actually an instance of a subclass of :class:`tuple`. This |
| 92 | class has the following additional read-only convenience attributes: |
| 93 | |
| 94 | +------------------+-------+--------------------------+----------------------+ |
| 95 | | Attribute | Index | Value | Value if not present | |
| 96 | +==================+=======+==========================+======================+ |
Berker Peksag | 89584c9 | 2015-06-25 23:38:48 +0300 | [diff] [blame] | 97 | | :attr:`scheme` | 0 | URL scheme specifier | *scheme* parameter | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 98 | +------------------+-------+--------------------------+----------------------+ |
| 99 | | :attr:`netloc` | 1 | Network location part | empty string | |
| 100 | +------------------+-------+--------------------------+----------------------+ |
| 101 | | :attr:`path` | 2 | Hierarchical path | empty string | |
| 102 | +------------------+-------+--------------------------+----------------------+ |
| 103 | | :attr:`params` | 3 | Parameters for last path | empty string | |
| 104 | | | | element | | |
| 105 | +------------------+-------+--------------------------+----------------------+ |
| 106 | | :attr:`query` | 4 | Query component | empty string | |
| 107 | +------------------+-------+--------------------------+----------------------+ |
| 108 | | :attr:`fragment` | 5 | Fragment identifier | empty string | |
| 109 | +------------------+-------+--------------------------+----------------------+ |
| 110 | | :attr:`username` | | User name | :const:`None` | |
| 111 | +------------------+-------+--------------------------+----------------------+ |
| 112 | | :attr:`password` | | Password | :const:`None` | |
| 113 | +------------------+-------+--------------------------+----------------------+ |
| 114 | | :attr:`hostname` | | Host name (lower case) | :const:`None` | |
| 115 | +------------------+-------+--------------------------+----------------------+ |
| 116 | | :attr:`port` | | Port number as integer, | :const:`None` | |
| 117 | | | | if present | | |
| 118 | +------------------+-------+--------------------------+----------------------+ |
| 119 | |
Robert Collins | dfa95c9 | 2015-08-10 09:53:30 +1200 | [diff] [blame] | 120 | Reading the :attr:`port` attribute will raise a :exc:`ValueError` if |
| 121 | an invalid port is specified in the URL. See section |
| 122 | :ref:`urlparse-result-object` for more information on the result object. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 123 | |
Howie Benefiel | f6e863d | 2017-05-15 23:48:16 -0500 | [diff] [blame^] | 124 | Unmatched square brackets in the :attr:`netloc` attribute will raise a |
| 125 | :exc:`ValueError`. |
| 126 | |
Senthil Kumaran | 7a1e09f | 2010-04-22 12:19:46 +0000 | [diff] [blame] | 127 | .. versionchanged:: 3.2 |
| 128 | Added IPv6 URL parsing capabilities. |
| 129 | |
Georg Brandl | a79b8dc | 2012-09-29 08:59:23 +0200 | [diff] [blame] | 130 | .. versionchanged:: 3.3 |
| 131 | The fragment is now parsed for all URL schemes (unless *allow_fragment* is |
| 132 | false), in accordance with :rfc:`3986`. Previously, a whitelist of |
| 133 | schemes that support fragments existed. |
| 134 | |
Robert Collins | dfa95c9 | 2015-08-10 09:53:30 +1200 | [diff] [blame] | 135 | .. versionchanged:: 3.6 |
| 136 | Out-of-range port numbers now raise :exc:`ValueError`, instead of |
| 137 | returning :const:`None`. |
| 138 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 139 | |
Victor Stinner | ac71c54 | 2011-01-14 12:52:12 +0000 | [diff] [blame] | 140 | .. function:: parse_qs(qs, keep_blank_values=False, strict_parsing=False, encoding='utf-8', errors='replace') |
Facundo Batista | c469d4c | 2008-09-03 22:49:01 +0000 | [diff] [blame] | 141 | |
| 142 | Parse a query string given as a string argument (data of type |
| 143 | :mimetype:`application/x-www-form-urlencoded`). Data are returned as a |
| 144 | dictionary. The dictionary keys are the unique query variable names and the |
| 145 | values are lists of values for each name. |
| 146 | |
| 147 | The optional argument *keep_blank_values* is a flag indicating whether blank |
Senthil Kumaran | f0769e8 | 2010-08-09 19:53:52 +0000 | [diff] [blame] | 148 | values in percent-encoded queries should be treated as blank strings. A true value |
Facundo Batista | c469d4c | 2008-09-03 22:49:01 +0000 | [diff] [blame] | 149 | indicates that blanks should be retained as blank strings. The default false |
| 150 | value indicates that blank values are to be ignored and treated as if they were |
| 151 | not included. |
| 152 | |
| 153 | The optional argument *strict_parsing* is a flag indicating what to do with |
| 154 | parsing errors. If false (the default), errors are silently ignored. If true, |
| 155 | errors raise a :exc:`ValueError` exception. |
| 156 | |
Victor Stinner | ac71c54 | 2011-01-14 12:52:12 +0000 | [diff] [blame] | 157 | The optional *encoding* and *errors* parameters specify how to decode |
| 158 | percent-encoded sequences into Unicode characters, as accepted by the |
| 159 | :meth:`bytes.decode` method. |
| 160 | |
Michael Foord | 207d229 | 2012-09-28 14:40:44 +0100 | [diff] [blame] | 161 | Use the :func:`urllib.parse.urlencode` function (with the ``doseq`` |
| 162 | parameter set to ``True``) to convert such dictionaries into query |
| 163 | strings. |
Facundo Batista | c469d4c | 2008-09-03 22:49:01 +0000 | [diff] [blame] | 164 | |
Senthil Kumaran | 2933312 | 2011-02-11 11:25:47 +0000 | [diff] [blame] | 165 | |
Victor Stinner | c58be2d | 2011-01-14 13:31:45 +0000 | [diff] [blame] | 166 | .. versionchanged:: 3.2 |
| 167 | Add *encoding* and *errors* parameters. |
| 168 | |
Facundo Batista | c469d4c | 2008-09-03 22:49:01 +0000 | [diff] [blame] | 169 | |
Victor Stinner | ac71c54 | 2011-01-14 12:52:12 +0000 | [diff] [blame] | 170 | .. function:: parse_qsl(qs, keep_blank_values=False, strict_parsing=False, encoding='utf-8', errors='replace') |
Facundo Batista | c469d4c | 2008-09-03 22:49:01 +0000 | [diff] [blame] | 171 | |
| 172 | Parse a query string given as a string argument (data of type |
| 173 | :mimetype:`application/x-www-form-urlencoded`). Data are returned as a list of |
| 174 | name, value pairs. |
| 175 | |
| 176 | The optional argument *keep_blank_values* is a flag indicating whether blank |
Senthil Kumaran | f0769e8 | 2010-08-09 19:53:52 +0000 | [diff] [blame] | 177 | values in percent-encoded queries should be treated as blank strings. A true value |
Facundo Batista | c469d4c | 2008-09-03 22:49:01 +0000 | [diff] [blame] | 178 | indicates that blanks should be retained as blank strings. The default false |
| 179 | value indicates that blank values are to be ignored and treated as if they were |
| 180 | not included. |
| 181 | |
| 182 | The optional argument *strict_parsing* is a flag indicating what to do with |
| 183 | parsing errors. If false (the default), errors are silently ignored. If true, |
| 184 | errors raise a :exc:`ValueError` exception. |
| 185 | |
Victor Stinner | ac71c54 | 2011-01-14 12:52:12 +0000 | [diff] [blame] | 186 | The optional *encoding* and *errors* parameters specify how to decode |
| 187 | percent-encoded sequences into Unicode characters, as accepted by the |
| 188 | :meth:`bytes.decode` method. |
| 189 | |
Facundo Batista | c469d4c | 2008-09-03 22:49:01 +0000 | [diff] [blame] | 190 | Use the :func:`urllib.parse.urlencode` function to convert such lists of pairs into |
| 191 | query strings. |
| 192 | |
Victor Stinner | c58be2d | 2011-01-14 13:31:45 +0000 | [diff] [blame] | 193 | .. versionchanged:: 3.2 |
| 194 | Add *encoding* and *errors* parameters. |
| 195 | |
Facundo Batista | c469d4c | 2008-09-03 22:49:01 +0000 | [diff] [blame] | 196 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 197 | .. function:: urlunparse(parts) |
| 198 | |
Georg Brandl | 0f7ede4 | 2008-06-23 11:23:31 +0000 | [diff] [blame] | 199 | Construct a URL from a tuple as returned by ``urlparse()``. The *parts* |
| 200 | argument can be any six-item iterable. This may result in a slightly |
| 201 | different, but equivalent URL, if the URL that was parsed originally had |
| 202 | unnecessary delimiters (for example, a ``?`` with an empty query; the RFC |
| 203 | states that these are equivalent). |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 204 | |
| 205 | |
R. David Murray | f5077aa | 2010-05-25 15:36:46 +0000 | [diff] [blame] | 206 | .. function:: urlsplit(urlstring, scheme='', allow_fragments=True) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 207 | |
| 208 | This is similar to :func:`urlparse`, but does not split the params from the URL. |
| 209 | This should generally be used instead of :func:`urlparse` if the more recent URL |
| 210 | syntax allowing parameters to be applied to each segment of the *path* portion |
| 211 | of the URL (see :rfc:`2396`) is wanted. A separate function is needed to |
| 212 | separate the path segments and parameters. This function returns a 5-tuple: |
| 213 | (addressing scheme, network location, path, query, fragment identifier). |
| 214 | |
| 215 | The return value is actually an instance of a subclass of :class:`tuple`. This |
| 216 | class has the following additional read-only convenience attributes: |
| 217 | |
| 218 | +------------------+-------+-------------------------+----------------------+ |
| 219 | | Attribute | Index | Value | Value if not present | |
| 220 | +==================+=======+=========================+======================+ |
Berker Peksag | 89584c9 | 2015-06-25 23:38:48 +0300 | [diff] [blame] | 221 | | :attr:`scheme` | 0 | URL scheme specifier | *scheme* parameter | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 222 | +------------------+-------+-------------------------+----------------------+ |
| 223 | | :attr:`netloc` | 1 | Network location part | empty string | |
| 224 | +------------------+-------+-------------------------+----------------------+ |
| 225 | | :attr:`path` | 2 | Hierarchical path | empty string | |
| 226 | +------------------+-------+-------------------------+----------------------+ |
| 227 | | :attr:`query` | 3 | Query component | empty string | |
| 228 | +------------------+-------+-------------------------+----------------------+ |
| 229 | | :attr:`fragment` | 4 | Fragment identifier | empty string | |
| 230 | +------------------+-------+-------------------------+----------------------+ |
| 231 | | :attr:`username` | | User name | :const:`None` | |
| 232 | +------------------+-------+-------------------------+----------------------+ |
| 233 | | :attr:`password` | | Password | :const:`None` | |
| 234 | +------------------+-------+-------------------------+----------------------+ |
| 235 | | :attr:`hostname` | | Host name (lower case) | :const:`None` | |
| 236 | +------------------+-------+-------------------------+----------------------+ |
| 237 | | :attr:`port` | | Port number as integer, | :const:`None` | |
| 238 | | | | if present | | |
| 239 | +------------------+-------+-------------------------+----------------------+ |
| 240 | |
Robert Collins | dfa95c9 | 2015-08-10 09:53:30 +1200 | [diff] [blame] | 241 | Reading the :attr:`port` attribute will raise a :exc:`ValueError` if |
| 242 | an invalid port is specified in the URL. See section |
| 243 | :ref:`urlparse-result-object` for more information on the result object. |
| 244 | |
Howie Benefiel | f6e863d | 2017-05-15 23:48:16 -0500 | [diff] [blame^] | 245 | Unmatched square brackets in the :attr:`netloc` attribute will raise a |
| 246 | :exc:`ValueError`. |
| 247 | |
Robert Collins | dfa95c9 | 2015-08-10 09:53:30 +1200 | [diff] [blame] | 248 | .. versionchanged:: 3.6 |
| 249 | Out-of-range port numbers now raise :exc:`ValueError`, instead of |
| 250 | returning :const:`None`. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 251 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 252 | |
| 253 | .. function:: urlunsplit(parts) |
| 254 | |
Georg Brandl | 0f7ede4 | 2008-06-23 11:23:31 +0000 | [diff] [blame] | 255 | Combine the elements of a tuple as returned by :func:`urlsplit` into a |
| 256 | complete URL as a string. The *parts* argument can be any five-item |
| 257 | iterable. This may result in a slightly different, but equivalent URL, if the |
| 258 | URL that was parsed originally had unnecessary delimiters (for example, a ? |
| 259 | with an empty query; the RFC states that these are equivalent). |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 260 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 261 | |
Georg Brandl | 7f01a13 | 2009-09-16 15:58:14 +0000 | [diff] [blame] | 262 | .. function:: urljoin(base, url, allow_fragments=True) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 263 | |
| 264 | Construct a full ("absolute") URL by combining a "base URL" (*base*) with |
| 265 | another URL (*url*). Informally, this uses components of the base URL, in |
Georg Brandl | 0f7ede4 | 2008-06-23 11:23:31 +0000 | [diff] [blame] | 266 | particular the addressing scheme, the network location and (part of) the |
| 267 | path, to provide missing components in the relative URL. For example: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 268 | |
Senthil Kumaran | aca8fd7 | 2008-06-23 04:41:59 +0000 | [diff] [blame] | 269 | >>> from urllib.parse import urljoin |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 270 | >>> urljoin('http://www.cwi.nl/%7Eguido/Python.html', 'FAQ.html') |
| 271 | 'http://www.cwi.nl/%7Eguido/FAQ.html' |
| 272 | |
| 273 | The *allow_fragments* argument has the same meaning and default as for |
| 274 | :func:`urlparse`. |
| 275 | |
| 276 | .. note:: |
| 277 | |
| 278 | If *url* is an absolute URL (that is, starting with ``//`` or ``scheme://``), |
| 279 | the *url*'s host name and/or scheme will be present in the result. For example: |
| 280 | |
Christian Heimes | fe337bf | 2008-03-23 21:54:12 +0000 | [diff] [blame] | 281 | .. doctest:: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 282 | |
| 283 | >>> urljoin('http://www.cwi.nl/%7Eguido/Python.html', |
| 284 | ... '//www.python.org/%7Eguido') |
| 285 | 'http://www.python.org/%7Eguido' |
| 286 | |
| 287 | If you do not want that behavior, preprocess the *url* with :func:`urlsplit` and |
| 288 | :func:`urlunsplit`, removing possible *scheme* and *netloc* parts. |
| 289 | |
| 290 | |
Antoine Pitrou | 55ac5b3 | 2014-08-21 19:16:17 -0400 | [diff] [blame] | 291 | .. versionchanged:: 3.5 |
| 292 | |
| 293 | Behaviour updated to match the semantics defined in :rfc:`3986`. |
| 294 | |
| 295 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 296 | .. function:: urldefrag(url) |
| 297 | |
Georg Brandl | 0f7ede4 | 2008-06-23 11:23:31 +0000 | [diff] [blame] | 298 | If *url* contains a fragment identifier, return a modified version of *url* |
| 299 | with no fragment identifier, and the fragment identifier as a separate |
| 300 | string. If there is no fragment identifier in *url*, return *url* unmodified |
| 301 | and an empty string. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 302 | |
Nick Coghlan | 9fc443c | 2010-11-30 15:48:08 +0000 | [diff] [blame] | 303 | The return value is actually an instance of a subclass of :class:`tuple`. This |
| 304 | class has the following additional read-only convenience attributes: |
| 305 | |
| 306 | +------------------+-------+-------------------------+----------------------+ |
| 307 | | Attribute | Index | Value | Value if not present | |
| 308 | +==================+=======+=========================+======================+ |
| 309 | | :attr:`url` | 0 | URL with no fragment | empty string | |
| 310 | +------------------+-------+-------------------------+----------------------+ |
| 311 | | :attr:`fragment` | 1 | Fragment identifier | empty string | |
| 312 | +------------------+-------+-------------------------+----------------------+ |
| 313 | |
| 314 | See section :ref:`urlparse-result-object` for more information on the result |
| 315 | object. |
| 316 | |
| 317 | .. versionchanged:: 3.2 |
Raymond Hettinger | 9a236b0 | 2011-01-24 09:01:27 +0000 | [diff] [blame] | 318 | Result is a structured object rather than a simple 2-tuple. |
Nick Coghlan | 9fc443c | 2010-11-30 15:48:08 +0000 | [diff] [blame] | 319 | |
Georg Brandl | 009a6bd | 2011-01-24 19:59:08 +0000 | [diff] [blame] | 320 | .. _parsing-ascii-encoded-bytes: |
Nick Coghlan | 9fc443c | 2010-11-30 15:48:08 +0000 | [diff] [blame] | 321 | |
| 322 | Parsing ASCII Encoded Bytes |
| 323 | --------------------------- |
| 324 | |
| 325 | The URL parsing functions were originally designed to operate on character |
| 326 | strings only. In practice, it is useful to be able to manipulate properly |
| 327 | quoted and encoded URLs as sequences of ASCII bytes. Accordingly, the |
| 328 | URL parsing functions in this module all operate on :class:`bytes` and |
| 329 | :class:`bytearray` objects in addition to :class:`str` objects. |
| 330 | |
| 331 | If :class:`str` data is passed in, the result will also contain only |
| 332 | :class:`str` data. If :class:`bytes` or :class:`bytearray` data is |
| 333 | passed in, the result will contain only :class:`bytes` data. |
| 334 | |
| 335 | Attempting to mix :class:`str` data with :class:`bytes` or |
| 336 | :class:`bytearray` in a single function call will result in a |
Éric Araujo | ff2a4ba | 2010-11-30 17:20:31 +0000 | [diff] [blame] | 337 | :exc:`TypeError` being raised, while attempting to pass in non-ASCII |
Nick Coghlan | 9fc443c | 2010-11-30 15:48:08 +0000 | [diff] [blame] | 338 | byte values will trigger :exc:`UnicodeDecodeError`. |
| 339 | |
| 340 | To support easier conversion of result objects between :class:`str` and |
| 341 | :class:`bytes`, all return values from URL parsing functions provide |
| 342 | either an :meth:`encode` method (when the result contains :class:`str` |
| 343 | data) or a :meth:`decode` method (when the result contains :class:`bytes` |
| 344 | data). The signatures of these methods match those of the corresponding |
| 345 | :class:`str` and :class:`bytes` methods (except that the default encoding |
| 346 | is ``'ascii'`` rather than ``'utf-8'``). Each produces a value of a |
| 347 | corresponding type that contains either :class:`bytes` data (for |
| 348 | :meth:`encode` methods) or :class:`str` data (for |
| 349 | :meth:`decode` methods). |
| 350 | |
| 351 | Applications that need to operate on potentially improperly quoted URLs |
| 352 | that may contain non-ASCII data will need to do their own decoding from |
| 353 | bytes to characters before invoking the URL parsing methods. |
| 354 | |
| 355 | The behaviour described in this section applies only to the URL parsing |
| 356 | functions. The URL quoting functions use their own rules when producing |
| 357 | or consuming byte sequences as detailed in the documentation of the |
| 358 | individual URL quoting functions. |
| 359 | |
| 360 | .. versionchanged:: 3.2 |
| 361 | URL parsing functions now accept ASCII encoded byte sequences |
| 362 | |
| 363 | |
| 364 | .. _urlparse-result-object: |
| 365 | |
| 366 | Structured Parse Results |
| 367 | ------------------------ |
| 368 | |
| 369 | The result objects from the :func:`urlparse`, :func:`urlsplit` and |
Georg Brandl | 4640237 | 2010-12-04 19:06:18 +0000 | [diff] [blame] | 370 | :func:`urldefrag` functions are subclasses of the :class:`tuple` type. |
Nick Coghlan | 9fc443c | 2010-11-30 15:48:08 +0000 | [diff] [blame] | 371 | These subclasses add the attributes listed in the documentation for |
| 372 | those functions, the encoding and decoding support described in the |
| 373 | previous section, as well as an additional method: |
| 374 | |
| 375 | .. method:: urllib.parse.SplitResult.geturl() |
| 376 | |
| 377 | Return the re-combined version of the original URL as a string. This may |
| 378 | differ from the original URL in that the scheme may be normalized to lower |
| 379 | case and empty components may be dropped. Specifically, empty parameters, |
| 380 | queries, and fragment identifiers will be removed. |
| 381 | |
| 382 | For :func:`urldefrag` results, only empty fragment identifiers will be removed. |
| 383 | For :func:`urlsplit` and :func:`urlparse` results, all noted changes will be |
| 384 | made to the URL returned by this method. |
| 385 | |
| 386 | The result of this method remains unchanged if passed back through the original |
| 387 | parsing function: |
| 388 | |
| 389 | >>> from urllib.parse import urlsplit |
| 390 | >>> url = 'HTTP://www.Python.org/doc/#' |
| 391 | >>> r1 = urlsplit(url) |
| 392 | >>> r1.geturl() |
| 393 | 'http://www.Python.org/doc/' |
| 394 | >>> r2 = urlsplit(r1.geturl()) |
| 395 | >>> r2.geturl() |
| 396 | 'http://www.Python.org/doc/' |
| 397 | |
| 398 | |
| 399 | The following classes provide the implementations of the structured parse |
| 400 | results when operating on :class:`str` objects: |
| 401 | |
| 402 | .. class:: DefragResult(url, fragment) |
| 403 | |
| 404 | Concrete class for :func:`urldefrag` results containing :class:`str` |
| 405 | data. The :meth:`encode` method returns a :class:`DefragResultBytes` |
| 406 | instance. |
| 407 | |
| 408 | .. versionadded:: 3.2 |
| 409 | |
| 410 | .. class:: ParseResult(scheme, netloc, path, params, query, fragment) |
| 411 | |
| 412 | Concrete class for :func:`urlparse` results containing :class:`str` |
| 413 | data. The :meth:`encode` method returns a :class:`ParseResultBytes` |
| 414 | instance. |
| 415 | |
| 416 | .. class:: SplitResult(scheme, netloc, path, query, fragment) |
| 417 | |
| 418 | Concrete class for :func:`urlsplit` results containing :class:`str` |
| 419 | data. The :meth:`encode` method returns a :class:`SplitResultBytes` |
| 420 | instance. |
| 421 | |
| 422 | |
| 423 | The following classes provide the implementations of the parse results when |
| 424 | operating on :class:`bytes` or :class:`bytearray` objects: |
| 425 | |
| 426 | .. class:: DefragResultBytes(url, fragment) |
| 427 | |
| 428 | Concrete class for :func:`urldefrag` results containing :class:`bytes` |
| 429 | data. The :meth:`decode` method returns a :class:`DefragResult` |
| 430 | instance. |
| 431 | |
| 432 | .. versionadded:: 3.2 |
| 433 | |
| 434 | .. class:: ParseResultBytes(scheme, netloc, path, params, query, fragment) |
| 435 | |
| 436 | Concrete class for :func:`urlparse` results containing :class:`bytes` |
| 437 | data. The :meth:`decode` method returns a :class:`ParseResult` |
| 438 | instance. |
| 439 | |
| 440 | .. versionadded:: 3.2 |
| 441 | |
| 442 | .. class:: SplitResultBytes(scheme, netloc, path, query, fragment) |
| 443 | |
| 444 | Concrete class for :func:`urlsplit` results containing :class:`bytes` |
| 445 | data. The :meth:`decode` method returns a :class:`SplitResult` |
| 446 | instance. |
| 447 | |
| 448 | .. versionadded:: 3.2 |
| 449 | |
| 450 | |
| 451 | URL Quoting |
| 452 | ----------- |
| 453 | |
| 454 | The URL quoting functions focus on taking program data and making it safe |
| 455 | for use as URL components by quoting special characters and appropriately |
| 456 | encoding non-ASCII text. They also support reversing these operations to |
| 457 | recreate the original data from the contents of a URL component if that |
| 458 | task isn't already covered by the URL parsing functions above. |
Georg Brandl | 7f01a13 | 2009-09-16 15:58:14 +0000 | [diff] [blame] | 459 | |
| 460 | .. function:: quote(string, safe='/', encoding=None, errors=None) |
Senthil Kumaran | aca8fd7 | 2008-06-23 04:41:59 +0000 | [diff] [blame] | 461 | |
| 462 | Replace special characters in *string* using the ``%xx`` escape. Letters, |
Ratnadeep Debnath | 21024f0 | 2017-02-25 14:30:28 +0530 | [diff] [blame] | 463 | digits, and the characters ``'_.-~'`` are never quoted. By default, this |
Senthil Kumaran | 8aa8bbe | 2009-08-31 16:43:45 +0000 | [diff] [blame] | 464 | function is intended for quoting the path section of URL. The optional *safe* |
Guido van Rossum | 52dbbb9 | 2008-08-18 21:44:30 +0000 | [diff] [blame] | 465 | parameter specifies additional ASCII characters that should not be quoted |
| 466 | --- its default value is ``'/'``. |
Senthil Kumaran | aca8fd7 | 2008-06-23 04:41:59 +0000 | [diff] [blame] | 467 | |
Guido van Rossum | 52dbbb9 | 2008-08-18 21:44:30 +0000 | [diff] [blame] | 468 | *string* may be either a :class:`str` or a :class:`bytes`. |
| 469 | |
Ratnadeep Debnath | 21024f0 | 2017-02-25 14:30:28 +0530 | [diff] [blame] | 470 | .. versionchanged:: 3.7 |
| 471 | Moved from RFC 2396 to RFC 3986 for quoting URL strings. "~" is now |
| 472 | included in the set of reserved characters. |
| 473 | |
Guido van Rossum | 52dbbb9 | 2008-08-18 21:44:30 +0000 | [diff] [blame] | 474 | The optional *encoding* and *errors* parameters specify how to deal with |
| 475 | non-ASCII characters, as accepted by the :meth:`str.encode` method. |
| 476 | *encoding* defaults to ``'utf-8'``. |
| 477 | *errors* defaults to ``'strict'``, meaning unsupported characters raise a |
| 478 | :class:`UnicodeEncodeError`. |
| 479 | *encoding* and *errors* must not be supplied if *string* is a |
| 480 | :class:`bytes`, or a :class:`TypeError` is raised. |
| 481 | |
| 482 | Note that ``quote(string, safe, encoding, errors)`` is equivalent to |
| 483 | ``quote_from_bytes(string.encode(encoding, errors), safe)``. |
| 484 | |
| 485 | Example: ``quote('/El Niño/')`` yields ``'/El%20Ni%C3%B1o/'``. |
Senthil Kumaran | aca8fd7 | 2008-06-23 04:41:59 +0000 | [diff] [blame] | 486 | |
| 487 | |
Georg Brandl | 7f01a13 | 2009-09-16 15:58:14 +0000 | [diff] [blame] | 488 | .. function:: quote_plus(string, safe='', encoding=None, errors=None) |
Senthil Kumaran | aca8fd7 | 2008-06-23 04:41:59 +0000 | [diff] [blame] | 489 | |
Georg Brandl | 0f7ede4 | 2008-06-23 11:23:31 +0000 | [diff] [blame] | 490 | Like :func:`quote`, but also replace spaces by plus signs, as required for |
Georg Brandl | 81c09db | 2009-07-29 07:27:08 +0000 | [diff] [blame] | 491 | quoting HTML form values when building up a query string to go into a URL. |
| 492 | Plus signs in the original string are escaped unless they are included in |
| 493 | *safe*. It also does not have *safe* default to ``'/'``. |
Senthil Kumaran | aca8fd7 | 2008-06-23 04:41:59 +0000 | [diff] [blame] | 494 | |
Guido van Rossum | 52dbbb9 | 2008-08-18 21:44:30 +0000 | [diff] [blame] | 495 | Example: ``quote_plus('/El Niño/')`` yields ``'%2FEl+Ni%C3%B1o%2F'``. |
Senthil Kumaran | aca8fd7 | 2008-06-23 04:41:59 +0000 | [diff] [blame] | 496 | |
Georg Brandl | 7f01a13 | 2009-09-16 15:58:14 +0000 | [diff] [blame] | 497 | |
| 498 | .. function:: quote_from_bytes(bytes, safe='/') |
Guido van Rossum | 52dbbb9 | 2008-08-18 21:44:30 +0000 | [diff] [blame] | 499 | |
| 500 | Like :func:`quote`, but accepts a :class:`bytes` object rather than a |
| 501 | :class:`str`, and does not perform string-to-bytes encoding. |
| 502 | |
| 503 | Example: ``quote_from_bytes(b'a&\xef')`` yields |
| 504 | ``'a%26%EF'``. |
| 505 | |
Georg Brandl | 7f01a13 | 2009-09-16 15:58:14 +0000 | [diff] [blame] | 506 | |
| 507 | .. function:: unquote(string, encoding='utf-8', errors='replace') |
Senthil Kumaran | aca8fd7 | 2008-06-23 04:41:59 +0000 | [diff] [blame] | 508 | |
| 509 | Replace ``%xx`` escapes by their single-character equivalent. |
Guido van Rossum | 52dbbb9 | 2008-08-18 21:44:30 +0000 | [diff] [blame] | 510 | The optional *encoding* and *errors* parameters specify how to decode |
| 511 | percent-encoded sequences into Unicode characters, as accepted by the |
| 512 | :meth:`bytes.decode` method. |
Senthil Kumaran | aca8fd7 | 2008-06-23 04:41:59 +0000 | [diff] [blame] | 513 | |
Guido van Rossum | 52dbbb9 | 2008-08-18 21:44:30 +0000 | [diff] [blame] | 514 | *string* must be a :class:`str`. |
| 515 | |
| 516 | *encoding* defaults to ``'utf-8'``. |
| 517 | *errors* defaults to ``'replace'``, meaning invalid sequences are replaced |
| 518 | by a placeholder character. |
| 519 | |
| 520 | Example: ``unquote('/El%20Ni%C3%B1o/')`` yields ``'/El Niño/'``. |
Senthil Kumaran | aca8fd7 | 2008-06-23 04:41:59 +0000 | [diff] [blame] | 521 | |
| 522 | |
Georg Brandl | 7f01a13 | 2009-09-16 15:58:14 +0000 | [diff] [blame] | 523 | .. function:: unquote_plus(string, encoding='utf-8', errors='replace') |
Senthil Kumaran | aca8fd7 | 2008-06-23 04:41:59 +0000 | [diff] [blame] | 524 | |
Georg Brandl | 0f7ede4 | 2008-06-23 11:23:31 +0000 | [diff] [blame] | 525 | Like :func:`unquote`, but also replace plus signs by spaces, as required for |
Senthil Kumaran | aca8fd7 | 2008-06-23 04:41:59 +0000 | [diff] [blame] | 526 | unquoting HTML form values. |
| 527 | |
Guido van Rossum | 52dbbb9 | 2008-08-18 21:44:30 +0000 | [diff] [blame] | 528 | *string* must be a :class:`str`. |
| 529 | |
| 530 | Example: ``unquote_plus('/El+Ni%C3%B1o/')`` yields ``'/El Niño/'``. |
| 531 | |
Georg Brandl | 7f01a13 | 2009-09-16 15:58:14 +0000 | [diff] [blame] | 532 | |
Guido van Rossum | 52dbbb9 | 2008-08-18 21:44:30 +0000 | [diff] [blame] | 533 | .. function:: unquote_to_bytes(string) |
| 534 | |
| 535 | Replace ``%xx`` escapes by their single-octet equivalent, and return a |
| 536 | :class:`bytes` object. |
| 537 | |
| 538 | *string* may be either a :class:`str` or a :class:`bytes`. |
| 539 | |
| 540 | If it is a :class:`str`, unescaped non-ASCII characters in *string* |
| 541 | are encoded into UTF-8 bytes. |
| 542 | |
Nick Coghlan | 9fc443c | 2010-11-30 15:48:08 +0000 | [diff] [blame] | 543 | Example: ``unquote_to_bytes('a%26%EF')`` yields ``b'a&\xef'``. |
Guido van Rossum | 52dbbb9 | 2008-08-18 21:44:30 +0000 | [diff] [blame] | 544 | |
Senthil Kumaran | aca8fd7 | 2008-06-23 04:41:59 +0000 | [diff] [blame] | 545 | |
R David Murray | c17686f | 2015-05-17 20:44:50 -0400 | [diff] [blame] | 546 | .. function:: urlencode(query, doseq=False, safe='', encoding=None, \ |
| 547 | errors=None, quote_via=quote_plus) |
Senthil Kumaran | aca8fd7 | 2008-06-23 04:41:59 +0000 | [diff] [blame] | 548 | |
Senthil Kumaran | df022da | 2010-07-03 17:48:22 +0000 | [diff] [blame] | 549 | Convert a mapping object or a sequence of two-element tuples, which may |
Martin Panter | cda85a0 | 2015-11-24 22:33:18 +0000 | [diff] [blame] | 550 | contain :class:`str` or :class:`bytes` objects, to a percent-encoded ASCII |
| 551 | text string. If the resultant string is to be used as a *data* for POST |
| 552 | operation with the :func:`~urllib.request.urlopen` function, then |
| 553 | it should be encoded to bytes, otherwise it would result in a |
| 554 | :exc:`TypeError`. |
Senthil Kumaran | 6b3434a | 2012-03-15 18:11:16 -0700 | [diff] [blame] | 555 | |
Senthil Kumaran | df022da | 2010-07-03 17:48:22 +0000 | [diff] [blame] | 556 | The resulting string is a series of ``key=value`` pairs separated by ``'&'`` |
R David Murray | c17686f | 2015-05-17 20:44:50 -0400 | [diff] [blame] | 557 | characters, where both *key* and *value* are quoted using the *quote_via* |
| 558 | function. By default, :func:`quote_plus` is used to quote the values, which |
| 559 | means spaces are quoted as a ``'+'`` character and '/' characters are |
| 560 | encoded as ``%2F``, which follows the standard for GET requests |
| 561 | (``application/x-www-form-urlencoded``). An alternate function that can be |
| 562 | passed as *quote_via* is :func:`quote`, which will encode spaces as ``%20`` |
| 563 | and not encode '/' characters. For maximum control of what is quoted, use |
| 564 | ``quote`` and specify a value for *safe*. |
| 565 | |
| 566 | When a sequence of two-element tuples is used as the *query* |
Senthil Kumaran | df022da | 2010-07-03 17:48:22 +0000 | [diff] [blame] | 567 | argument, the first element of each tuple is a key and the second is a |
| 568 | value. The value element in itself can be a sequence and in that case, if |
Serhiy Storchaka | a97cd2e | 2016-10-19 16:43:42 +0300 | [diff] [blame] | 569 | the optional parameter *doseq* is evaluates to ``True``, individual |
Senthil Kumaran | df022da | 2010-07-03 17:48:22 +0000 | [diff] [blame] | 570 | ``key=value`` pairs separated by ``'&'`` are generated for each element of |
| 571 | the value sequence for the key. The order of parameters in the encoded |
Nick Coghlan | 9fc443c | 2010-11-30 15:48:08 +0000 | [diff] [blame] | 572 | string will match the order of parameter tuples in the sequence. |
Senthil Kumaran | df022da | 2010-07-03 17:48:22 +0000 | [diff] [blame] | 573 | |
R David Murray | 8c4e112 | 2014-12-24 21:23:18 -0500 | [diff] [blame] | 574 | The *safe*, *encoding*, and *errors* parameters are passed down to |
R David Murray | c17686f | 2015-05-17 20:44:50 -0400 | [diff] [blame] | 575 | *quote_via* (the *encoding* and *errors* parameters are only passed |
R David Murray | 8c4e112 | 2014-12-24 21:23:18 -0500 | [diff] [blame] | 576 | when a query element is a :class:`str`). |
Nick Coghlan | 9fc443c | 2010-11-30 15:48:08 +0000 | [diff] [blame] | 577 | |
| 578 | To reverse this encoding process, :func:`parse_qs` and :func:`parse_qsl` are |
| 579 | provided in this module to parse query strings into Python data structures. |
Senthil Kumaran | df022da | 2010-07-03 17:48:22 +0000 | [diff] [blame] | 580 | |
Senthil Kumaran | 2933312 | 2011-02-11 11:25:47 +0000 | [diff] [blame] | 581 | Refer to :ref:`urllib examples <urllib-examples>` to find out how urlencode |
| 582 | method can be used for generating query string for a URL or data for POST. |
| 583 | |
Senthil Kumaran | df022da | 2010-07-03 17:48:22 +0000 | [diff] [blame] | 584 | .. versionchanged:: 3.2 |
Georg Brandl | 67b21b7 | 2010-08-17 15:07:14 +0000 | [diff] [blame] | 585 | Query parameter supports bytes and string objects. |
Senthil Kumaran | aca8fd7 | 2008-06-23 04:41:59 +0000 | [diff] [blame] | 586 | |
R David Murray | c17686f | 2015-05-17 20:44:50 -0400 | [diff] [blame] | 587 | .. versionadded:: 3.5 |
| 588 | *quote_via* parameter. |
| 589 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 590 | |
| 591 | .. seealso:: |
| 592 | |
Senthil Kumaran | 6257bdd | 2010-04-22 05:53:18 +0000 | [diff] [blame] | 593 | :rfc:`3986` - Uniform Resource Identifiers |
Senthil Kumaran | fe9230a | 2011-06-19 13:52:49 -0700 | [diff] [blame] | 594 | This is the current standard (STD66). Any changes to urllib.parse module |
Senthil Kumaran | 6257bdd | 2010-04-22 05:53:18 +0000 | [diff] [blame] | 595 | should conform to this. Certain deviations could be observed, which are |
Georg Brandl | 6faee4e | 2010-09-21 14:48:28 +0000 | [diff] [blame] | 596 | mostly for backward compatibility purposes and for certain de-facto |
Senthil Kumaran | 6257bdd | 2010-04-22 05:53:18 +0000 | [diff] [blame] | 597 | parsing requirements as commonly observed in major browsers. |
| 598 | |
| 599 | :rfc:`2732` - Format for Literal IPv6 Addresses in URL's. |
| 600 | This specifies the parsing requirements of IPv6 URLs. |
| 601 | |
| 602 | :rfc:`2396` - Uniform Resource Identifiers (URI): Generic Syntax |
| 603 | Document describing the generic syntactic requirements for both Uniform Resource |
| 604 | Names (URNs) and Uniform Resource Locators (URLs). |
| 605 | |
| 606 | :rfc:`2368` - The mailto URL scheme. |
Martin Panter | fe289c0 | 2016-05-28 02:20:39 +0000 | [diff] [blame] | 607 | Parsing requirements for mailto URL schemes. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 608 | |
| 609 | :rfc:`1808` - Relative Uniform Resource Locators |
| 610 | This Request For Comments includes the rules for joining an absolute and a |
| 611 | relative URL, including a fair number of "Abnormal Examples" which govern the |
| 612 | treatment of border cases. |
| 613 | |
Senthil Kumaran | 6257bdd | 2010-04-22 05:53:18 +0000 | [diff] [blame] | 614 | :rfc:`1738` - Uniform Resource Locators (URL) |
| 615 | This specifies the formal syntax and semantics of absolute URLs. |