blob: 3901a9cf760ffb71b93b0a564df916efebed8650 [file] [log] [blame]
Fred Drake295da241998-08-10 19:42:37 +00001\section{\module{urllib} ---
Fred Drakedfca4dc2000-08-25 05:13:42 +00002 Open arbitrary resources by URL}
Fred Drakeb91e9341998-07-23 17:59:49 +00003
Fred Drake38e5d272000-04-03 20:13:55 +00004\declaremodule{standard}{urllib}
5\modulesynopsis{Open an arbitrary network resource by URL (requires sockets).}
Fred Drakeb91e9341998-07-23 17:59:49 +00006
Guido van Rossuma8db1df1995-02-16 16:29:46 +00007\index{WWW}
Guido van Rossum470be141995-03-17 16:07:09 +00008\index{World-Wide Web}
Guido van Rossum61d34f41995-02-27 17:51:51 +00009\index{URL}
Guido van Rossuma8db1df1995-02-16 16:29:46 +000010
Guido van Rossum86751151995-02-28 17:14:32 +000011
Guido van Rossuma8db1df1995-02-16 16:29:46 +000012This module provides a high-level interface for fetching data across
Fred Drake6ef871c1998-03-12 06:52:05 +000013the World-Wide Web. In particular, the \function{urlopen()} function
14is similar to the built-in function \function{open()}, but accepts
15Universal Resource Locators (URLs) instead of filenames. Some
16restrictions apply --- it can only open URLs for reading, and no seek
17operations are available.
Guido van Rossuma8db1df1995-02-16 16:29:46 +000018
Fred Drakef5eaa2e1997-12-15 22:13:50 +000019It defines the following public functions:
Guido van Rossuma8db1df1995-02-16 16:29:46 +000020
Guido van Rossum0af2f631998-07-22 21:34:21 +000021\begin{funcdesc}{urlopen}{url\optional{, data}}
Guido van Rossuma8db1df1995-02-16 16:29:46 +000022Open a network object denoted by a URL for reading. If the URL does
Fred Drake6ef871c1998-03-12 06:52:05 +000023not have a scheme identifier, or if it has \file{file:} as its scheme
Guido van Rossuma8db1df1995-02-16 16:29:46 +000024identifier, this opens a local file; otherwise it opens a socket to a
25server somewhere on the network. If the connection cannot be made, or
Fred Drake6ef871c1998-03-12 06:52:05 +000026if the server returns an error code, the \exception{IOError} exception
27is raised. If all went well, a file-like object is returned. This
28supports the following methods: \method{read()}, \method{readline()},
Fred Drake1ec71cb1999-02-22 22:42:14 +000029\method{readlines()}, \method{fileno()}, \method{close()},
30\method{info()} and \method{geturl()}.
Guido van Rossum0af2f631998-07-22 21:34:21 +000031
Fred Drake1ec71cb1999-02-22 22:42:14 +000032Except for the \method{info()} and \method{geturl()} methods,
Guido van Rossum0af2f631998-07-22 21:34:21 +000033these methods have the same interface as for
Fred Drake6ef871c1998-03-12 06:52:05 +000034file objects --- see section \ref{bltin-file-objects} in this
35manual. (It is not a built-in file object, however, so it can't be
Guido van Rossum470be141995-03-17 16:07:09 +000036used at those few places where a true built-in file object is
37required.)
Guido van Rossuma8db1df1995-02-16 16:29:46 +000038
Fred Drake6ef871c1998-03-12 06:52:05 +000039The \method{info()} method returns an instance of the class
Guido van Rossum954b9ad1998-09-28 14:08:29 +000040\class{mimetools.Message} containing meta-information associated
41with the URL. When the method is HTTP, these headers are those
42returned by the server at the head of the retrieved HTML page
43(including Content-Length and Content-Type). When the method is FTP,
44a Content-Length header will be present if (as is now usual) the
45server passed back a file length in response to the FTP retrieval
46request. When the method is local-file, returned headers will include
47a Date representing the file's last-modified time, a Content-Length
48giving file size, and a Content-Type containing a guess at the file's
49type. See also the description of the
Fred Drake1ec71cb1999-02-22 22:42:14 +000050\refmodule{mimetools}\refstmodindex{mimetools} module.
51
52The \method{geturl()} method returns the real URL of the page. In
53some cases, the HTTP server redirects a client to another URL. The
54\function{urlopen()} function handles this transparently, but in some
55cases the caller needs to know which URL the client was redirected
56to. The \method{geturl()} method can be used to get at this
57redirected URL.
Guido van Rossum0af2f631998-07-22 21:34:21 +000058
59If the \var{url} uses the \file{http:} scheme identifier, the optional
60\var{data} argument may be given to specify a \code{POST} request
61(normally the request type is \code{GET}). The \var{data} argument
62must in standard \file{application/x-www-form-urlencoded} format;
63see the \function{urlencode()} function below.
64
Fred Drakeaef0e892000-08-31 17:23:35 +000065The \function{urlopen()} function works transparently with proxies
Fred Drake81c17352000-09-15 04:12:56 +000066which do not require authentication. In a \UNIX{} or Windows
Fred Drakeaef0e892000-08-31 17:23:35 +000067environment, set the \envvar{http_proxy}, \envvar{ftp_proxy} or
68\envvar{gopher_proxy} environment variables to a URL that identifies
69the proxy server before starting the Python interpreter. For example
70(the \character{\%} is the command prompt):
Fred Drake38e5d272000-04-03 20:13:55 +000071
72\begin{verbatim}
73% http_proxy="http://www.someproxy.com:3128"
74% export http_proxy
75% python
76...
77\end{verbatim}
78
79In a Macintosh environment, \function{urlopen()} will retrieve proxy
80information from Internet\index{Internet Config} Config.
81
Fred Drakeaef0e892000-08-31 17:23:35 +000082Proxies which require authentication for use are not currently
83supported; this is considered an implementation limitation.
84
Fred Drake38e5d272000-04-03 20:13:55 +000085The \function{urlopen()} function works transparently with proxies.
86In a \UNIX{} or Windows environment, set the \envvar{http_proxy},
87\envvar{ftp_proxy} or \envvar{gopher_proxy} environment variables to a
88URL that identifies the proxy server before starting the Python
89interpreter, e.g.:
90
91\begin{verbatim}
92% http_proxy="http://www.someproxy.com:3128"
93% export http_proxy
94% python
95...
96\end{verbatim}
97
98In a Macintosh environment, \function{urlopen()} will retrieve proxy
99information from Internet Config.
Guido van Rossuma8db1df1995-02-16 16:29:46 +0000100\end{funcdesc}
101
Fred Drake1ec71cb1999-02-22 22:42:14 +0000102\begin{funcdesc}{urlretrieve}{url\optional{, filename\optional{, hook}}}
Guido van Rossuma8db1df1995-02-16 16:29:46 +0000103Copy a network object denoted by a URL to a local file, if necessary.
Guido van Rossum6c4f0031995-03-07 10:14:09 +0000104If the URL points to a local file, or a valid cached copy of the
Fred Drake6ef871c1998-03-12 06:52:05 +0000105object exists, the object is not copied. Return a tuple
106\code{(\var{filename}, \var{headers})} where \var{filename} is the
107local file name under which the object can be found, and \var{headers}
108is either \code{None} (for a local object) or whatever the
109\method{info()} method of the object returned by \function{urlopen()}
110returned (for a remote object, possibly cached). Exceptions are the
111same as for \function{urlopen()}.
Guido van Rossum954b9ad1998-09-28 14:08:29 +0000112
113The second argument, if present, specifies the file location to copy
114to (if absent, the location will be a tempfile with a generated name).
115The third argument, if present, is a hook function that will be called
116once on establishment of the network connection and once after each
117block read thereafter. The hook will be passed three arguments; a
118count of blocks transferred so far, a block size in bytes, and the
Fred Drake09b29571998-10-01 20:43:13 +0000119total size of the file. The third argument may be \code{-1} on older
120FTP servers which do not return a file size in response to a retrieval
Guido van Rossum954b9ad1998-09-28 14:08:29 +0000121request.
Fred Drake9fa4d612000-08-24 01:06:40 +0000122
123If the \var{url} uses the \file{http:} scheme identifier, the optional
124\var{data} argument may be given to specify a \code{POST} request
125(normally the request type is \code{GET}). The \var{data} argument
126must in standard \file{application/x-www-form-urlencoded} format;
127see the \function{urlencode()} function below.
Guido van Rossuma8db1df1995-02-16 16:29:46 +0000128\end{funcdesc}
129
130\begin{funcdesc}{urlcleanup}{}
131Clear the cache that may have been built up by previous calls to
Fred Drake6ef871c1998-03-12 06:52:05 +0000132\function{urlretrieve()}.
Guido van Rossuma8db1df1995-02-16 16:29:46 +0000133\end{funcdesc}
134
Guido van Rossum0af2f631998-07-22 21:34:21 +0000135\begin{funcdesc}{quote}{string\optional{, safe}}
Fred Drake6ef871c1998-03-12 06:52:05 +0000136Replace special characters in \var{string} using the \samp{\%xx} escape.
137Letters, digits, and the characters \character{_,.-} are never quoted.
Guido van Rossum0af2f631998-07-22 21:34:21 +0000138The optional \var{safe} parameter specifies additional characters
Guido van Rossum61d34f41995-02-27 17:51:51 +0000139that should not be quoted --- its default value is \code{'/'}.
140
Fred Drake10853c92000-07-28 13:51:27 +0000141Example: \code{quote('/\~{}connolly/')} yields \code{'/\%7econnolly/'}.
Guido van Rossum8d40c841996-12-13 14:48:47 +0000142\end{funcdesc}
143
Guido van Rossum0af2f631998-07-22 21:34:21 +0000144\begin{funcdesc}{quote_plus}{string\optional{, safe}}
Fred Drake6ef871c1998-03-12 06:52:05 +0000145Like \function{quote()}, but also replaces spaces by plus signs, as
Guido van Rossum0af2f631998-07-22 21:34:21 +0000146required for quoting HTML form values. Plus signs in the original
147string are escaped unless they are included in \var{safe}.
Guido van Rossum61d34f41995-02-27 17:51:51 +0000148\end{funcdesc}
149
150\begin{funcdesc}{unquote}{string}
Guido van Rossum6c4f0031995-03-07 10:14:09 +0000151Replace \samp{\%xx} escapes by their single-character equivalent.
Guido van Rossum61d34f41995-02-27 17:51:51 +0000152
Fred Drake10853c92000-07-28 13:51:27 +0000153Example: \code{unquote('/\%7Econnolly/')} yields \code{'/\~{}connolly/'}.
Guido van Rossum61d34f41995-02-27 17:51:51 +0000154\end{funcdesc}
155
Guido van Rossum8d40c841996-12-13 14:48:47 +0000156\begin{funcdesc}{unquote_plus}{string}
Fred Drake6ef871c1998-03-12 06:52:05 +0000157Like \function{unquote()}, but also replaces plus signs by spaces, as
Guido van Rossum8d40c841996-12-13 14:48:47 +0000158required for unquoting HTML form values.
159\end{funcdesc}
160
Guido van Rossum0af2f631998-07-22 21:34:21 +0000161\begin{funcdesc}{urlencode}{dict}
162Convert a dictionary to a ``url-encoded'' string, suitable to pass to
163\function{urlopen()} above as the optional \var{data} argument. This
164is useful to pass a dictionary of form fields to a \code{POST}
Fred Drake09b29571998-10-01 20:43:13 +0000165request. The resulting string is a series of
166\code{\var{key}=\var{value}} pairs separated by \character{\&}
167characters, where both \var{key} and \var{value} are quoted using
168\function{quote_plus()} above.
Guido van Rossum0af2f631998-07-22 21:34:21 +0000169\end{funcdesc}
170
Fred Drakedfca4dc2000-08-25 05:13:42 +0000171The public functions \function{urlopen()} and
172\function{urlretrieve()} create an instance of the
173\class{FancyURLopener} class and use it to perform their requested
174actions. To override this functionality, programmers can create a
175subclass of \class{URLopener} or \class{FancyURLopener}, then assign
176that an instance of that class to the
177\code{urllib._urlopener} variable before calling the desired function.
178For example, applications may want to specify a different
Fred Drake38e5d272000-04-03 20:13:55 +0000179\code{user-agent} header than \class{URLopener} defines. This can be
180accomplished with the following code:
181
182\begin{verbatim}
183class AppURLopener(urllib.FancyURLopener):
184 def __init__(self, *args):
Fred Drake38e5d272000-04-03 20:13:55 +0000185 self.version = "App/1.7"
Guido van Rossum3d0c77b2000-08-24 16:20:32 +0000186 apply(urllib.FancyURLopener.__init__, (self,) + args)
Fred Drake38e5d272000-04-03 20:13:55 +0000187
Fred Drake6c160192000-05-30 14:39:45 +0000188urllib._urlopener = AppURLopener()
Fred Drake38e5d272000-04-03 20:13:55 +0000189\end{verbatim}
190
191\begin{classdesc}{URLopener}{\optional{proxies\optional{, **x509}}}
192Base class for opening and reading URLs. Unless you need to support
193opening objects using schemes other than \file{http:}, \file{ftp:},
194\file{gopher:} or \file{file:}, you probably want to use
195\class{FancyURLopener}.
196
197By default, the \class{URLopener} class sends a
198\code{user-agent} header of \samp{urllib/\var{VVV}}, where
199\var{VVV} is the \module{urllib} version number. Applications can
200define their own \code{user-agent} header by subclassing
201\class{URLopener} or \class{FancyURLopener} and setting the instance
Fred Drakedfca4dc2000-08-25 05:13:42 +0000202attribute \member{version} to an appropriate string value before the
Fred Drake38e5d272000-04-03 20:13:55 +0000203\method{open()} method is called.
204
205Additional keyword parameters, collected in \var{x509}, are used for
206authentication with the \file{https:} scheme. The keywords
207\var{key_file} and \var{cert_file} are supported; both are needed to
208actually retrieve a resource at an \file{https:} URL.
209\end{classdesc}
210
211\begin{classdesc}{FancyURLopener}{...}
212\class{FancyURLopener} subclasses \class{URLopener} providing default
213handling for the following HTTP response codes: 301, 302 or 401. For
214301 and 302 response codes, the \code{location} header is used to
215fetch the actual URL. For 401 response codes (authentication
216required), basic HTTP authentication is performed.
217
218The parameters to the constructor are the same as those for
219\class{URLopener}.
220\end{classdesc}
221
Guido van Rossuma8db1df1995-02-16 16:29:46 +0000222Restrictions:
223
224\begin{itemize}
225
226\item
227Currently, only the following protocols are supported: HTTP, (versions
2280.9 and 1.0), Gopher (but not Gopher-+), FTP, and local files.
Fred Drake6ef871c1998-03-12 06:52:05 +0000229\indexii{HTTP}{protocol}
230\indexii{Gopher}{protocol}
231\indexii{FTP}{protocol}
Guido van Rossuma8db1df1995-02-16 16:29:46 +0000232
233\item
Fred Drake6ef871c1998-03-12 06:52:05 +0000234The caching feature of \function{urlretrieve()} has been disabled
235until I find the time to hack proper processing of Expiration time
236headers.
Guido van Rossuma8db1df1995-02-16 16:29:46 +0000237
238\item
Guido van Rossum6c4f0031995-03-07 10:14:09 +0000239There should be a function to query whether a particular URL is in
Guido van Rossuma8db1df1995-02-16 16:29:46 +0000240the cache.
241
242\item
243For backward compatibility, if a URL appears to point to a local file
244but the file can't be opened, the URL is re-interpreted using the FTP
245protocol. This can sometimes cause confusing error messages.
246
247\item
Fred Drake6ef871c1998-03-12 06:52:05 +0000248The \function{urlopen()} and \function{urlretrieve()} functions can
249cause arbitrarily long delays while waiting for a network connection
250to be set up. This means that it is difficult to build an interactive
Guido van Rossuma8db1df1995-02-16 16:29:46 +0000251web client using these functions without using threads.
252
253\item
Fred Drake6ef871c1998-03-12 06:52:05 +0000254The data returned by \function{urlopen()} or \function{urlretrieve()}
255is the raw data returned by the server. This may be binary data
Fred Drake1ec71cb1999-02-22 22:42:14 +0000256(e.g. an image), plain text or (for example) HTML\index{HTML}. The
257HTTP\indexii{HTTP}{protocol} protocol provides type information in the
258reply header, which can be inspected by looking at the
259\code{content-type} header. For the Gopher\indexii{Gopher}{protocol}
260protocol, type information is encoded in the URL; there is currently
261no easy way to extract it. If the returned data is HTML, you can use
262the module \refmodule{htmllib}\refstmodindex{htmllib} to parse it.
Guido van Rossuma8db1df1995-02-16 16:29:46 +0000263
264\item
Fred Drake81c17352000-09-15 04:12:56 +0000265This module does not support the use of proxies which require
266authentication. This may be implemented in the future.
267
268\item
Fred Drake6ef871c1998-03-12 06:52:05 +0000269Although the \module{urllib} module contains (undocumented) routines
270to parse and unparse URL strings, the recommended interface for URL
Fred Drake1ec71cb1999-02-22 22:42:14 +0000271manipulation is in module \refmodule{urlparse}\refstmodindex{urlparse}.
Guido van Rossuma8db1df1995-02-16 16:29:46 +0000272
273\end{itemize}
Fred Drake38e5d272000-04-03 20:13:55 +0000274
275
276\subsection{URLopener Objects \label{urlopener-objs}}
277\sectionauthor{Skip Montanaro}{skip@mojam.com}
278
279\class{URLopener} and \class{FancyURLopener} objects have the
Fred Drakedfca4dc2000-08-25 05:13:42 +0000280following attributes.
Fred Drake38e5d272000-04-03 20:13:55 +0000281
Fred Drakedfca4dc2000-08-25 05:13:42 +0000282\begin{methoddesc}[URLopener]{open}{fullurl\optional{, data}}
Fred Drake38e5d272000-04-03 20:13:55 +0000283Open \var{fullurl} using the appropriate protocol. This method sets
284up cache and proxy information, then calls the appropriate open method with
285its input arguments. If the scheme is not recognized,
286\method{open_unknown()} is called. The \var{data} argument
287has the same meaning as the \var{data} argument of \function{urlopen()}.
288\end{methoddesc}
289
Fred Drakedfca4dc2000-08-25 05:13:42 +0000290\begin{methoddesc}[URLopener]{open_unknown}{fullurl\optional{, data}}
Fred Drake38e5d272000-04-03 20:13:55 +0000291Overridable interface to open unknown URL types.
292\end{methoddesc}
293
Fred Drakedfca4dc2000-08-25 05:13:42 +0000294\begin{methoddesc}[URLopener]{retrieve}{url\optional{,
295 filename\optional{,
296 reporthook\optional{, data}}}}
Fred Drake38e5d272000-04-03 20:13:55 +0000297Retrieves the contents of \var{url} and places it in \var{filename}. The
298return value is a tuple consisting of a local filename and either a
299\class{mimetools.Message} object containing the response headers (for remote
300URLs) or None (for local URLs). The caller must then open and read the
301contents of \var{filename}. If \var{filename} is not given and the URL
302refers to a local file, the input filename is returned. If the URL is
303non-local and \var{filename} is not given, the filename is the output of
304\function{tempfile.mktemp()} with a suffix that matches the suffix of the last
305path component of the input URL. If \var{reporthook} is given, it must be
306a function accepting three numeric parameters. It will be called after each
307chunk of data is read from the network. \var{reporthook} is ignored for
308local URLs.
Fred Drake9fa4d612000-08-24 01:06:40 +0000309
310If the \var{url} uses the \file{http:} scheme identifier, the optional
311\var{data} argument may be given to specify a \code{POST} request
312(normally the request type is \code{GET}). The \var{data} argument
313must in standard \file{application/x-www-form-urlencoded} format;
314see the \function{urlencode()} function below.
Fred Drake38e5d272000-04-03 20:13:55 +0000315\end{methoddesc}
316
Fred Drakedfca4dc2000-08-25 05:13:42 +0000317\begin{memberdesc}[URLopener]{version}
318Variable that specifies the user agent of the opener object. To get
319\refmodule{urllib} to tell servers that it is a particular user agent,
320set this in a subclass as a class variable or in the constructor
321before calling the base constructor.
322\end{memberdesc}
323
Fred Drake38e5d272000-04-03 20:13:55 +0000324
325\subsection{Examples}
326\nodename{Urllib Examples}
327
328Here is an example session that uses the \samp{GET} method to retrieve
329a URL containing parameters:
330
331\begin{verbatim}
332>>> import urllib
333>>> params = urllib.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0})
334>>> f = urllib.urlopen("http://www.musi-cal.com/cgi-bin/query?%s" % params)
335>>> print f.read()
336\end{verbatim}
337
338The following example uses the \samp{POST} method instead:
339
340\begin{verbatim}
341>>> import urllib
342>>> params = urllib.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0})
343>>> f = urllib.urlopen("http://www.musi-cal.com/cgi-bin/query", params)
344>>> print f.read()
345\end{verbatim}