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