| 1 |
: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 |
|
| 15 |
.. note:: |
| 16 |
The :mod:`urlparse` module is renamed to :mod:`urllib.parse` in Python 3. |
| 17 |
The :term:`2to3` tool will automatically adapt imports when converting |
| 18 |
your sources to Python 3. |
| 19 |
|
| 20 |
**Source code:** :source:`Lib/urlparse.py` |
| 21 |
|
| 22 |
-------------- |
| 23 |
|
| 24 |
This module defines a standard interface to break Uniform Resource Locator (URL) |
| 25 |
strings up in components (addressing scheme, network location, path etc.), to |
| 26 |
combine the components back into a URL string, and to convert a "relative URL" |
| 27 |
to an absolute URL given a "base URL." |
| 28 |
|
| 29 |
The module has been designed to match the Internet RFC on Relative Uniform |
| 30 |
Resource Locators. It supports the following URL schemes: ``file``, ``ftp``, |
| 31 |
``gopher``, ``hdl``, ``http``, ``https``, ``imap``, ``mailto``, ``mms``, |
| 32 |
``news``, ``nntp``, ``prospero``, ``rsync``, ``rtsp``, ``rtspu``, ``sftp``, |
| 33 |
``shttp``, ``sip``, ``sips``, ``snews``, ``svn``, ``svn+ssh``, ``telnet``, |
| 34 |
``wais``. |
| 35 |
|
| 36 |
.. versionadded:: 2.5 |
| 37 |
Support for the ``sftp`` and ``sips`` schemes. |
| 38 |
|
| 39 |
The :mod:`urlparse` module defines the following functions: |
| 40 |
|
| 41 |
|
| 42 |
.. function:: urlparse(urlstring[, scheme[, allow_fragments]]) |
| 43 |
|
| 44 |
Parse a URL into six components, returning a 6-tuple. This corresponds to the |
| 45 |
general structure of a URL: ``scheme://netloc/path;parameters?query#fragment``. |
| 46 |
Each tuple item is a string, possibly empty. The components are not broken up in |
| 47 |
smaller parts (for example, the network location is a single string), and % |
| 48 |
escapes are not expanded. The delimiters as shown above are not part of the |
| 49 |
result, except for a leading slash in the *path* component, which is retained if |
| 50 |
present. For example: |
| 51 |
|
| 52 |
>>> from urlparse import urlparse |
| 53 |
>>> o = urlparse('http://www.cwi.nl:80/%7Eguido/Python.html') |
| 54 |
>>> o # doctest: +NORMALIZE_WHITESPACE |
| 55 |
ParseResult(scheme='http', netloc='www.cwi.nl:80', path='/%7Eguido/Python.html', |
| 56 |
params='', query='', fragment='') |
| 57 |
>>> o.scheme |
| 58 |
'http' |
| 59 |
>>> o.port |
| 60 |
80 |
| 61 |
>>> o.geturl() |
| 62 |
'http://www.cwi.nl:80/%7Eguido/Python.html' |
| 63 |
|
| 64 |
|
| 65 |
Following the syntax specifications in :rfc:`1808`, urlparse recognizes |
| 66 |
a netloc only if it is properly introduced by '//'. Otherwise the |
| 67 |
input is presumed to be a relative URL and thus to start with |
| 68 |
a path component. |
| 69 |
|
| 70 |
>>> from urlparse import urlparse |
| 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='') |
| 74 |
>>> urlparse('www.cwi.nl/%7Eguido/Python.html') |
| 75 |
ParseResult(scheme='', netloc='', path='www.cwi.nl/%7Eguido/Python.html', |
| 76 |
params='', query='', fragment='') |
| 77 |
>>> urlparse('help/Python.html') |
| 78 |
ParseResult(scheme='', netloc='', path='help/Python.html', params='', |
| 79 |
query='', fragment='') |
| 80 |
|
| 81 |
If the *scheme* argument is specified, it gives the default addressing |
| 82 |
scheme, to be used only if the URL does not specify one. The default value for |
| 83 |
this argument is the empty string. |
| 84 |
|
| 85 |
If the *allow_fragments* argument is false, fragment identifiers are not |
| 86 |
recognized and parsed as part of the preceding component, even if the URL's |
| 87 |
addressing scheme normally does support them. The default value for this |
| 88 |
argument is :const:`True`. |
| 89 |
|
| 90 |
The return value is actually an instance of a subclass of :class:`tuple`. This |
| 91 |
class has the following additional read-only convenience attributes: |
| 92 |
|
| 93 |
+------------------+-------+--------------------------+----------------------+ |
| 94 |
| Attribute | Index | Value | Value if not present | |
| 95 |
+==================+=======+==========================+======================+ |
| 96 |
| :attr:`scheme` | 0 | URL scheme specifier | *scheme* parameter | |
| 97 |
+------------------+-------+--------------------------+----------------------+ |
| 98 |
| :attr:`netloc` | 1 | Network location part | empty string | |
| 99 |
+------------------+-------+--------------------------+----------------------+ |
| 100 |
| :attr:`path` | 2 | Hierarchical path | empty string | |
| 101 |
+------------------+-------+--------------------------+----------------------+ |
| 102 |
| :attr:`params` | 3 | Parameters for last path | empty string | |
| 103 |
| | | element | | |
| 104 |
+------------------+-------+--------------------------+----------------------+ |
| 105 |
| :attr:`query` | 4 | Query component | empty string | |
| 106 |
+------------------+-------+--------------------------+----------------------+ |
| 107 |
| :attr:`fragment` | 5 | Fragment identifier | empty string | |
| 108 |
+------------------+-------+--------------------------+----------------------+ |
| 109 |
| :attr:`username` | | User name | :const:`None` | |
| 110 |
+------------------+-------+--------------------------+----------------------+ |
| 111 |
| :attr:`password` | | Password | :const:`None` | |
| 112 |
+------------------+-------+--------------------------+----------------------+ |
| 113 |
| :attr:`hostname` | | Host name (lower case) | :const:`None` | |
| 114 |
+------------------+-------+--------------------------+----------------------+ |
| 115 |
| :attr:`port` | | Port number as integer, | :const:`None` | |
| 116 |
| | | if present | | |
| 117 |
+------------------+-------+--------------------------+----------------------+ |
| 118 |
|
| 119 |
See section :ref:`urlparse-result-object` for more information on the result |
| 120 |
object. |
| 121 |
|
| 122 |
Characters in the :attr:`netloc` attribute that decompose under NFKC |
| 123 |
normalization (as used by the IDNA encoding) into any of ``/``, ``?``, |
| 124 |
``#``, ``@``, or ``:`` will raise a :exc:`ValueError`. If the URL is |
| 125 |
decomposed before parsing, or is not a Unicode string, no error will be |
| 126 |
raised. |
| 127 |
|
| 128 |
.. versionchanged:: 2.5 |
| 129 |
Added attributes to return value. |
| 130 |
|
| 131 |
.. versionchanged:: 2.7 |
| 132 |
Added IPv6 URL parsing capabilities. |
| 133 |
|
| 134 |
.. versionchanged:: 2.7.17 |
| 135 |
Characters that affect netloc parsing under NFKC normalization will |
| 136 |
now raise :exc:`ValueError`. |
| 137 |
|
| 138 |
|
| 139 |
.. function:: parse_qs(qs[, keep_blank_values[, strict_parsing[, max_num_fields]]]) |
| 140 |
|
| 141 |
Parse a query string given as a string argument (data of type |
| 142 |
:mimetype:`application/x-www-form-urlencoded`). Data are returned as a |
| 143 |
dictionary. The dictionary keys are the unique query variable names and the |
| 144 |
values are lists of values for each name. |
| 145 |
|
| 146 |
The optional argument *keep_blank_values* is a flag indicating whether blank |
| 147 |
values in percent-encoded queries should be treated as blank strings. A true value |
| 148 |
indicates that blanks should be retained as blank strings. The default false |
| 149 |
value indicates that blank values are to be ignored and treated as if they were |
| 150 |
not included. |
| 151 |
|
| 152 |
The optional argument *strict_parsing* is a flag indicating what to do with |
| 153 |
parsing errors. If false (the default), errors are silently ignored. If true, |
| 154 |
errors raise a :exc:`ValueError` exception. |
| 155 |
|
| 156 |
The optional argument *max_num_fields* is the maximum number of fields to |
| 157 |
read. If set, then throws a :exc:`ValueError` if there are more than |
| 158 |
*max_num_fields* fields read. |
| 159 |
|
| 160 |
Use the :func:`urllib.urlencode` function to convert such dictionaries into |
| 161 |
query strings. |
| 162 |
|
| 163 |
.. versionadded:: 2.6 |
| 164 |
Copied from the :mod:`cgi` module. |
| 165 |
|
| 166 |
.. versionchanged:: 2.7.16 |
| 167 |
Added *max_num_fields* parameter. |
| 168 |
|
| 169 |
.. function:: parse_qsl(qs[, keep_blank_values[, strict_parsing[, max_num_fields]]]) |
| 170 |
|
| 171 |
Parse a query string given as a string argument (data of type |
| 172 |
:mimetype:`application/x-www-form-urlencoded`). Data are returned as a list of |
| 173 |
name, value pairs. |
| 174 |
|
| 175 |
The optional argument *keep_blank_values* is a flag indicating whether blank |
| 176 |
values in percent-encoded queries should be treated as blank strings. A true value |
| 177 |
indicates that blanks should be retained as blank strings. The default false |
| 178 |
value indicates that blank values are to be ignored and treated as if they were |
| 179 |
not included. |
| 180 |
|
| 181 |
The optional argument *strict_parsing* is a flag indicating what to do with |
| 182 |
parsing errors. If false (the default), errors are silently ignored. If true, |
| 183 |
errors raise a :exc:`ValueError` exception. |
| 184 |
|
| 185 |
The optional argument *max_num_fields* is the maximum number of fields to |
| 186 |
read. If set, then throws a :exc:`ValueError` if there are more than |
| 187 |
*max_num_fields* fields read. |
| 188 |
|
| 189 |
Use the :func:`urllib.urlencode` function to convert such lists of pairs into |
| 190 |
query strings. |
| 191 |
|
| 192 |
.. versionadded:: 2.6 |
| 193 |
Copied from the :mod:`cgi` module. |
| 194 |
|
| 195 |
.. versionchanged:: 2.7.16 |
| 196 |
Added *max_num_fields* parameter. |
| 197 |
|
| 198 |
.. function:: urlunparse(parts) |
| 199 |
|
| 200 |
Construct a URL from a tuple as returned by ``urlparse()``. The *parts* argument |
| 201 |
can be any six-item iterable. This may result in a slightly different, but |
| 202 |
equivalent URL, if the URL that was parsed originally had unnecessary delimiters |
| 203 |
(for example, a ? with an empty query; the RFC states that these are |
| 204 |
equivalent). |
| 205 |
|
| 206 |
|
| 207 |
.. function:: urlsplit(urlstring[, scheme[, allow_fragments]]) |
| 208 |
|
| 209 |
This is similar to :func:`urlparse`, but does not split the params from the URL. |
| 210 |
This should generally be used instead of :func:`urlparse` if the more recent URL |
| 211 |
syntax allowing parameters to be applied to each segment of the *path* portion |
| 212 |
of the URL (see :rfc:`2396`) is wanted. A separate function is needed to |
| 213 |
separate the path segments and parameters. This function returns a 5-tuple: |
| 214 |
(addressing scheme, network location, path, query, fragment identifier). |
| 215 |
|
| 216 |
The return value is actually an instance of a subclass of :class:`tuple`. This |
| 217 |
class has the following additional read-only convenience attributes: |
| 218 |
|
| 219 |
+------------------+-------+-------------------------+----------------------+ |
| 220 |
| Attribute | Index | Value | Value if not present | |
| 221 |
+==================+=======+=========================+======================+ |
| 222 |
| :attr:`scheme` | 0 | URL scheme specifier | *scheme* parameter | |
| 223 |
+------------------+-------+-------------------------+----------------------+ |
| 224 |
| :attr:`netloc` | 1 | Network location part | empty string | |
| 225 |
+------------------+-------+-------------------------+----------------------+ |
| 226 |
| :attr:`path` | 2 | Hierarchical path | empty string | |
| 227 |
+------------------+-------+-------------------------+----------------------+ |
| 228 |
| :attr:`query` | 3 | Query component | empty string | |
| 229 |
+------------------+-------+-------------------------+----------------------+ |
| 230 |
| :attr:`fragment` | 4 | Fragment identifier | empty string | |
| 231 |
+------------------+-------+-------------------------+----------------------+ |
| 232 |
| :attr:`username` | | User name | :const:`None` | |
| 233 |
+------------------+-------+-------------------------+----------------------+ |
| 234 |
| :attr:`password` | | Password | :const:`None` | |
| 235 |
+------------------+-------+-------------------------+----------------------+ |
| 236 |
| :attr:`hostname` | | Host name (lower case) | :const:`None` | |
| 237 |
+------------------+-------+-------------------------+----------------------+ |
| 238 |
| :attr:`port` | | Port number as integer, | :const:`None` | |
| 239 |
| | | if present | | |
| 240 |
+------------------+-------+-------------------------+----------------------+ |
| 241 |
|
| 242 |
See section :ref:`urlparse-result-object` for more information on the result |
| 243 |
object. |
| 244 |
|
| 245 |
Characters in the :attr:`netloc` attribute that decompose under NFKC |
| 246 |
normalization (as used by the IDNA encoding) into any of ``/``, ``?``, |
| 247 |
``#``, ``@``, or ``:`` will raise a :exc:`ValueError`. If the URL is |
| 248 |
decomposed before parsing, or is not a Unicode string, no error will be |
| 249 |
raised. |
| 250 |
|
| 251 |
.. versionadded:: 2.2 |
| 252 |
|
| 253 |
.. versionchanged:: 2.5 |
| 254 |
Added attributes to return value. |
| 255 |
|
| 256 |
.. versionchanged:: 2.7.17 |
| 257 |
Characters that affect netloc parsing under NFKC normalization will |
| 258 |
now raise :exc:`ValueError`. |
| 259 |
|
| 260 |
|
| 261 |
.. function:: urlunsplit(parts) |
| 262 |
|
| 263 |
Combine the elements of a tuple as returned by :func:`urlsplit` into a complete |
| 264 |
URL as a string. The *parts* argument can be any five-item iterable. This may |
| 265 |
result in a slightly different, but equivalent URL, if the URL that was parsed |
| 266 |
originally had unnecessary delimiters (for example, a ? with an empty query; the |
| 267 |
RFC states that these are equivalent). |
| 268 |
|
| 269 |
.. versionadded:: 2.2 |
| 270 |
|
| 271 |
|
| 272 |
.. function:: urljoin(base, url[, allow_fragments]) |
| 273 |
|
| 274 |
Construct a full ("absolute") URL by combining a "base URL" (*base*) with |
| 275 |
another URL (*url*). Informally, this uses components of the base URL, in |
| 276 |
particular the addressing scheme, the network location and (part of) the path, |
| 277 |
to provide missing components in the relative URL. For example: |
| 278 |
|
| 279 |
>>> from urlparse import urljoin |
| 280 |
>>> urljoin('http://www.cwi.nl/%7Eguido/Python.html', 'FAQ.html') |
| 281 |
'http://www.cwi.nl/%7Eguido/FAQ.html' |
| 282 |
|
| 283 |
The *allow_fragments* argument has the same meaning and default as for |
| 284 |
:func:`urlparse`. |
| 285 |
|
| 286 |
.. note:: |
| 287 |
|
| 288 |
If *url* is an absolute URL (that is, starting with ``//`` or ``scheme://``), |
| 289 |
the *url*'s host name and/or scheme will be present in the result. For example: |
| 290 |
|
| 291 |
.. doctest:: |
| 292 |
|
| 293 |
>>> urljoin('http://www.cwi.nl/%7Eguido/Python.html', |
| 294 |
... '//www.python.org/%7Eguido') |
| 295 |
'http://www.python.org/%7Eguido' |
| 296 |
|
| 297 |
If you do not want that behavior, preprocess the *url* with :func:`urlsplit` and |
| 298 |
:func:`urlunsplit`, removing possible *scheme* and *netloc* parts. |
| 299 |
|
| 300 |
|
| 301 |
.. function:: urldefrag(url) |
| 302 |
|
| 303 |
If *url* contains a fragment identifier, returns a modified version of *url* |
| 304 |
with no fragment identifier, and the fragment identifier as a separate string. |
| 305 |
If there is no fragment identifier in *url*, returns *url* unmodified and an |
| 306 |
empty string. |
| 307 |
|
| 308 |
|
| 309 |
.. seealso:: |
| 310 |
|
| 311 |
:rfc:`3986` - Uniform Resource Identifiers |
| 312 |
This is the current standard (STD66). Any changes to urlparse module |
| 313 |
should conform to this. Certain deviations could be observed, which are |
| 314 |
mostly for backward compatibility purposes and for certain de-facto |
| 315 |
parsing requirements as commonly observed in major browsers. |
| 316 |
|
| 317 |
:rfc:`2732` - Format for Literal IPv6 Addresses in URL's. |
| 318 |
This specifies the parsing requirements of IPv6 URLs. |
| 319 |
|
| 320 |
:rfc:`2396` - Uniform Resource Identifiers (URI): Generic Syntax |
| 321 |
Document describing the generic syntactic requirements for both Uniform Resource |
| 322 |
Names (URNs) and Uniform Resource Locators (URLs). |
| 323 |
|
| 324 |
:rfc:`2368` - The mailto URL scheme. |
| 325 |
Parsing requirements for mailto URL schemes. |
| 326 |
|
| 327 |
:rfc:`1808` - Relative Uniform Resource Locators |
| 328 |
This Request For Comments includes the rules for joining an absolute and a |
| 329 |
relative URL, including a fair number of "Abnormal Examples" which govern the |
| 330 |
treatment of border cases. |
| 331 |
|
| 332 |
:rfc:`1738` - Uniform Resource Locators (URL) |
| 333 |
This specifies the formal syntax and semantics of absolute URLs. |
| 334 |
|
| 335 |
|
| 336 |
.. _urlparse-result-object: |
| 337 |
|
| 338 |
Results of :func:`urlparse` and :func:`urlsplit` |
| 339 |
------------------------------------------------ |
| 340 |
|
| 341 |
The result objects from the :func:`urlparse` and :func:`urlsplit` functions are |
| 342 |
subclasses of the :class:`tuple` type. These subclasses add the attributes |
| 343 |
described in those functions, as well as provide an additional method: |
| 344 |
|
| 345 |
|
| 346 |
.. method:: ParseResult.geturl() |
| 347 |
|
| 348 |
Return the re-combined version of the original URL as a string. This may differ |
| 349 |
from the original URL in that the scheme will always be normalized to lower case |
| 350 |
and empty components may be dropped. Specifically, empty parameters, queries, |
| 351 |
and fragment identifiers will be removed. |
| 352 |
|
| 353 |
The result of this method is a fixpoint if passed back through the original |
| 354 |
parsing function: |
| 355 |
|
| 356 |
>>> import urlparse |
| 357 |
>>> url = 'HTTP://www.Python.org/doc/#' |
| 358 |
|
| 359 |
>>> r1 = urlparse.urlsplit(url) |
| 360 |
>>> r1.geturl() |
| 361 |
'http://www.Python.org/doc/' |
| 362 |
|
| 363 |
>>> r2 = urlparse.urlsplit(r1.geturl()) |
| 364 |
>>> r2.geturl() |
| 365 |
'http://www.Python.org/doc/' |
| 366 |
|
| 367 |
.. versionadded:: 2.5 |
| 368 |
|
| 369 |
The following classes provide the implementations of the parse results: |
| 370 |
|
| 371 |
|
| 372 |
.. class:: ParseResult(scheme, netloc, path, params, query, fragment) |
| 373 |
|
| 374 |
Concrete class for :func:`urlparse` results. |
| 375 |
|
| 376 |
|
| 377 |
.. class:: SplitResult(scheme, netloc, path, query, fragment) |
| 378 |
|
| 379 |
Concrete class for :func:`urlsplit` results. |
| 380 |
|