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