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