cpython_sandbox / Doc / library / urllib.request.rst

:mod:`urllib.request` --- Extensible library for opening URLs

The :mod:`urllib.request` module defines functions and classes which help in opening URLs (mostly HTTP) in a complex world --- basic and digest authentication, redirections, cookies and more.

The :mod:`urllib.request` module defines the following functions:

The following classes are provided:

This class is an abstraction of a URL request.

url should be a string containing a valid URL.

data must be a bytes object specifying additional data to send to the server, or None if no such data is needed. Currently HTTP requests are the only ones that use data; the HTTP request will be a POST instead of a GET when the data parameter is provided. data should be a buffer in the standard :mimetype:`application/x-www-form-urlencoded` format.

The :func:`urllib.parse.urlencode` function takes a mapping or sequence of 2-tuples and returns a string in this format. It should be encoded to bytes before being used as the data parameter. The charset parameter in Content-Type header may be used to specify the encoding. If charset parameter is not sent with the Content-Type header, the server following the HTTP 1.1 recommendation may assume that the data is encoded in ISO-8859-1 encoding. It is advisable to use charset parameter with encoding used in Content-Type header with the :class:`Request`.

headers should be a dictionary, and will be treated as if :meth:`add_header` was called with each key and value as arguments. This is often used to "spoof" the User-Agent header, which is used by a browser to identify itself -- some HTTP servers only allow requests coming from common browsers as opposed to scripts. For example, Mozilla Firefox may identify itself as "Mozilla/5.0 (X11; U; Linux i686) Gecko/20071127 Firefox/", while :mod:`urllib`'s default user agent string is "Python-urllib/2.6" (on Python 2.6).

An example of using Content-Type header with data argument would be sending a dictionary like {"Content-Type":" application/x-www-form-urlencoded;charset=utf-8"}

The final two arguments are only of interest for correct handling of third-party HTTP cookies:

origin_req_host should be the request-host of the origin transaction, as defined by RFC 2965. It defaults to http.cookiejar.request_host(self). This is the host name or IP address of the original request that was initiated by the user. For example, if the request is for an image in an HTML document, this should be the request-host of the request for the page containing the image.

unverifiable should indicate whether the request is unverifiable, as defined by RFC 2965. It defaults to False. An unverifiable request is one whose URL the user did not have the option to approve. For example, if the request is for an image in an HTML document, and the user had no option to approve the automatic fetching of the image, this should be true.

method should be a string that indicates the HTTP request method that will be used (e.g. 'HEAD'). Its value is stored in the :attr:`~Request.method` attribute and is used by :meth:`get_method()`.

The :class:`OpenerDirector` class opens URLs via :class:`BaseHandler`s chained together. It manages the chaining of handlers, and recovery from errors.

This is the base class for all registered handlers --- and handles only the simple mechanics of registration.

A class which defines a default handler for HTTP error responses; all responses are turned into :exc:`HTTPError` exceptions.

A class to handle redirections.

A class to handle HTTP Cookies.

Cause requests to go through a proxy. If proxies is given, it must be a dictionary mapping protocol names to URLs of proxies. The default is to read the list of proxies from the environment variables :envvar:`<protocol>_proxy`. If no proxy environment variables are set, then in a Windows environment proxy settings are obtained from the registry's Internet Settings section, and in a Mac OS X environment proxy information is retrieved from the OS X System Configuration Framework.

To disable autodetected proxy pass an empty dictionary.

Keep a database of (realm, uri) -> (user, password) mappings.

Keep a database of (realm, uri) -> (user, password) mappings. A realm of None is considered a catch-all realm, which is searched if no other realm fits.

This is a mixin class that helps with HTTP authentication, both to the remote host and to a proxy. password_mgr, if given, should be something that is compatible with :class:`HTTPPasswordMgr`; refer to section :ref:`http-password-mgr` for information on the interface that must be supported.

Handle authentication with the remote host. password_mgr, if given, should be something that is compatible with :class:`HTTPPasswordMgr`; refer to section :ref:`http-password-mgr` for information on the interface that must be supported. HTTPBasicAuthHandler will raise a :exc:`ValueError` when presented with a wrong Authentication scheme.

Handle authentication with the proxy. password_mgr, if given, should be something that is compatible with :class:`HTTPPasswordMgr`; refer to section :ref:`http-password-mgr` for information on the interface that must be supported.

This is a mixin class that helps with HTTP authentication, both to the remote host and to a proxy. password_mgr, if given, should be something that is compatible with :class:`HTTPPasswordMgr`; refer to section :ref:`http-password-mgr` for information on the interface that must be supported.

Handle authentication with the remote host. password_mgr, if given, should be something that is compatible with :class:`HTTPPasswordMgr`; refer to section :ref:`http-password-mgr` for information on the interface that must be supported. When both Digest Authentication Handler and Basic Authentication Handler are both added, Digest Authentication is always tried first. If the Digest Authentication returns a 40x response again, it is sent to Basic Authentication handler to Handle. This Handler method will raise a :exc:`ValueError` when presented with an authentication scheme other than Digest or Basic.

Handle authentication with the proxy. password_mgr, if given, should be something that is compatible with :class:`HTTPPasswordMgr`; refer to section :ref:`http-password-mgr` for information on the interface that must be supported.

A class to handle opening of HTTP URLs.

A class to handle opening of HTTPS URLs. context and check_hostname have the same meaning as in :class:`http.client.HTTPSConnection`.

Open local files.

Open data URLs.

Open FTP URLs.

Open FTP URLs, keeping a cache of open FTP connections to minimize delays.

A catch-all class to handle unknown URLs.

Process HTTP error responses.

Request Objects

The following methods describe :class:`Request`'s public interface, and so all may be overridden in subclasses. It also defines several public attributes that can be used by clients to inspect the parsed request.

OpenerDirector Objects

:class:`OpenerDirector` instances have the following methods:

OpenerDirector objects open URLs in three stages:

The order in which these methods are called within each stage is determined by sorting the handler instances.

  1. Every handler with a method named like :meth:`protocol_request` has that method called to pre-process the request.

  2. Handlers with a method named like :meth:`protocol_open` are called to handle the request. This stage ends when a handler either returns a non-:const:`None` value (ie. a response), or raises an exception (usually :exc:`URLError`). Exceptions are allowed to propagate.

    In fact, the above algorithm is first tried for methods named :meth:`default_open`. If all such methods return :const:`None`, the algorithm is repeated for methods named like :meth:`protocol_open`. If all such methods return :const:`None`, the algorithm is repeated for methods named :meth:`unknown_open`.

    Note that the implementation of these methods may involve calls of the parent :class:`OpenerDirector` instance's :meth:`` and :meth:`~OpenerDirector.error` methods.

  3. Every handler with a method named like :meth:`protocol_response` has that method called to post-process the response.

BaseHandler Objects

:class:`BaseHandler` objects provide a couple of methods that are directly useful, and others that are meant to be used by derived classes. These are intended for direct use:

The following attribute and methods should only be used by classes derived from :class:`BaseHandler`.


The convention has been adopted that subclasses defining :meth:`protocol_request` or :meth:`protocol_response` methods are named :class:`\*Processor`; all others are named :class:`\*Handler`.

HTTPRedirectHandler Objects


Some HTTP redirections require action from this module's client code. If this is the case, :exc:`HTTPError` is raised. See RFC 2616 for details of the precise meanings of the various redirection codes.

An :class:`HTTPError` exception raised as a security consideration if the HTTPRedirectHandler is presented with a redirected url which is not an HTTP, HTTPS or FTP url.

HTTPCookieProcessor Objects

:class:`HTTPCookieProcessor` instances have one attribute:

ProxyHandler Objects

HTTPPasswordMgr Objects

These methods are available on :class:`HTTPPasswordMgr` and :class:`HTTPPasswordMgrWithDefaultRealm` objects.

AbstractBasicAuthHandler Objects

HTTPBasicAuthHandler Objects

ProxyBasicAuthHandler Objects

AbstractDigestAuthHandler Objects

HTTPDigestAuthHandler Objects

ProxyDigestAuthHandler Objects

HTTPHandler Objects

HTTPSHandler Objects

FileHandler Objects

DataHandler Objects

FTPHandler Objects

CacheFTPHandler Objects

:class:`CacheFTPHandler` objects are :class:`FTPHandler` objects with the following additional methods:

UnknownHandler Objects

HTTPErrorProcessor Objects


This example gets the main page and displays the first 300 bytes of it.

>>> import urllib.request
>>> f = urllib.request.urlopen('')
>>> print(
b'<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
xmlns="" xml:lang="en" lang="en">\n\n<head>\n
<meta http-equiv="content-type" content="text/html; charset=utf-8" />\n
<title>Python Programming '

Note that urlopen returns a bytes object. This is because there is no way for urlopen to automatically determine the encoding of the byte stream it receives from the http server. In general, a program will decode the returned bytes object to string once it determines or guesses the appropriate encoding.

The following W3C document, , lists the various ways in which a (X)HTML or a XML document could have specified its encoding information.

As the website uses utf-8 encoding as specified in it's meta tag, we will use the same for decoding the bytes object.

>>> with urllib.request.urlopen('') as f:
...     print('utf-8'))
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"

It is also possible to achieve the same result without using the :term:`context manager` approach.

>>> import urllib.request
>>> f = urllib.request.urlopen('')
>>> print('utf-8'))
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"

In the following example, we are sending a data-stream to the stdin of a CGI and reading the data it returns to us. Note that this example will only work when the Python installation supports SSL.

>>> import urllib.request
>>> req = urllib.request.Request(url='https://localhost/cgi-bin/test.cgi',
...                       data=b'This data is passed to stdin of the CGI')
>>> f = urllib.request.urlopen(req)
>>> print('utf-8'))
Got Data: "This data is passed to stdin of the CGI"

The code for the sample CGI used in the above example is:

#!/usr/bin/env python
import sys
data =
print('Content-type: text-plain\n\nGot Data: "%s"' % data)

Here is an example of doing a PUT request using :class:`Request`:

import urllib.request
DATA=b'some data'
req = urllib.request.Request(url='http://localhost:8080', data=DATA,method='PUT')
f = urllib.request.urlopen(req)

Use of Basic HTTP Authentication:

import urllib.request
# Create an OpenerDirector with support for Basic HTTP Authentication...
auth_handler = urllib.request.HTTPBasicAuthHandler()
auth_handler.add_password(realm='PDQ Application',
opener = urllib.request.build_opener(auth_handler)
# ...and install it globally so it can be used with urlopen.

:func:`build_opener` provides many handlers by default, including a :class:`ProxyHandler`. By default, :class:`ProxyHandler` uses the environment variables named <scheme>_proxy, where <scheme> is the URL scheme involved. For example, the :envvar:`http_proxy` environment variable is read to obtain the HTTP proxy's URL.

This example replaces the default :class:`ProxyHandler` with one that uses programmatically-supplied proxy URLs, and adds proxy authorization support with :class:`ProxyBasicAuthHandler`.

proxy_handler = urllib.request.ProxyHandler({'http': ''})
proxy_auth_handler = urllib.request.ProxyBasicAuthHandler()
proxy_auth_handler.add_password('realm', 'host', 'username', 'password')

opener = urllib.request.build_opener(proxy_handler, proxy_auth_handler)
# This time, rather than install the OpenerDirector, we use it directly:'')

Adding HTTP headers:

Use the headers argument to the :class:`Request` constructor, or:

import urllib.request
req = urllib.request.Request('')
req.add_header('Referer', '')
r = urllib.request.urlopen(req)

:class:`OpenerDirector` automatically adds a :mailheader:`User-Agent` header to every :class:`Request`. To change this:

import urllib.request
opener = urllib.request.build_opener()
opener.addheaders = [('User-agent', 'Mozilla/5.0')]'')

Also, remember that a few standard headers (:mailheader:`Content-Length`, :mailheader:`Content-Type` without charset parameter and :mailheader:`Host`) are added when the :class:`Request` is passed to :func:`urlopen` (or :meth:``).

Here is an example session that uses the GET method to retrieve a URL containing parameters:

>>> import urllib.request
>>> import urllib.parse
>>> params = urllib.parse.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0})
>>> f = urllib.request.urlopen("" % params)
>>> print('utf-8'))

The following example uses the POST method instead. Note that params output from urlencode is encoded to bytes before it is sent to urlopen as data:

>>> import urllib.request
>>> import urllib.parse
>>> data = urllib.parse.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0})
>>> data = data.encode('utf-8')
>>> request = urllib.request.Request("")
>>> # adding charset parameter to the Content-Type header.
>>> request.add_header("Content-Type","application/x-www-form-urlencoded;charset=utf-8")
>>> f = urllib.request.urlopen(request, data)
>>> print('utf-8'))

The following example uses an explicitly specified HTTP proxy, overriding environment settings:

>>> import urllib.request
>>> proxies = {'http': ''}
>>> opener = urllib.request.FancyURLopener(proxies)
>>> f ="")

The following example uses no proxies at all, overriding environment settings:

>>> import urllib.request
>>> opener = urllib.request.FancyURLopener({})
>>> f ="")

Legacy interface

The following functions and classes are ported from the Python 2 module urllib (as opposed to urllib2). They might become deprecated at some point in the future.

Base class for opening and reading URLs. Unless you need to support opening objects using schemes other than :file:`http:`, :file:`ftp:`, or :file:`file:`, you probably want to use :class:`FancyURLopener`.

By default, the :class:`URLopener` class sends a :mailheader:`User-Agent` header of urllib/VVV, where VVV is the :mod:`urllib` version number. Applications can define their own :mailheader:`User-Agent` header by subclassing :class:`URLopener` or :class:`FancyURLopener` and setting the class attribute :attr:`version` to an appropriate string value in the subclass definition.

The optional proxies parameter should be a dictionary mapping scheme names to proxy URLs, where an empty dictionary turns proxies off completely. Its default value is None, in which case environmental proxy settings will be used if present, as discussed in the definition of :func:`urlopen`, above.

Additional keyword parameters, collected in x509, may be used for authentication of the client when using the :file:`https:` scheme. The keywords key_file and cert_file are supported to provide an SSL key and certificate; both are needed to support client authentication.

:class:`URLopener` objects will raise an :exc:`OSError` exception if the server returns an error code.

:class:`FancyURLopener` subclasses :class:`URLopener` providing default handling for the following HTTP response codes: 301, 302, 303, 307 and 401. For the 30x response codes listed above, the :mailheader:`Location` header is used to fetch the actual URL. For 401 response codes (authentication required), basic HTTP authentication is performed. For the 30x response codes, recursion is bounded by the value of the maxtries attribute, which defaults to 10.

For all other response codes, the method :meth:`http_error_default` is called which you can override in subclasses to handle the error appropriately.


According to the letter of RFC 2616, 301 and 302 responses to POST requests must not be automatically redirected without confirmation by the user. In reality, browsers do allow automatic redirection of these responses, changing the POST to a GET, and :mod:`urllib` reproduces this behaviour.

The parameters to the constructor are the same as those for :class:`URLopener`.


When performing basic authentication, a :class:`FancyURLopener` instance calls its :meth:`prompt_user_passwd` method. The default implementation asks the users for the required information on the controlling terminal. A subclass may override this method to support more appropriate behavior if needed.

The :class:`FancyURLopener` class offers one additional method that should be overloaded to provide the appropriate behavior:

:mod:`urllib.request` Restrictions

  • Currently, only the following protocols are supported: HTTP (versions 0.9 and 1.0), FTP, local files, and data URLs.
  • The caching feature of :func:`urlretrieve` has been disabled until someone finds the time to hack proper processing of Expiration time headers.
  • There should be a function to query whether a particular URL is in the cache.
  • For backward compatibility, if a URL appears to point to a local file but the file can't be opened, the URL is re-interpreted using the FTP protocol. This can sometimes cause confusing error messages.
  • The :func:`urlopen` and :func:`urlretrieve` functions can cause arbitrarily long delays while waiting for a network connection to be set up. This means that it is difficult to build an interactive Web client using these functions without using threads.
  • The data returned by :func:`urlopen` or :func:`urlretrieve` is the raw data returned by the server. This may be binary data (such as an image), plain text or (for example) HTML. The HTTP protocol provides type information in the reply header, which can be inspected by looking at the :mailheader:`Content-Type` header. If the returned data is HTML, you can use the module :mod:`html.parser` to parse it.
  • The code handling the FTP protocol cannot differentiate between a file and a directory. This can lead to unexpected behavior when attempting to read a URL that points to a file that is not accessible. If the URL ends in a /, it is assumed to refer to a directory and will be handled accordingly. But if an attempt to read a file leads to a 550 error (meaning the URL cannot be found or is not accessible, often for permission reasons), then the path is treated as a directory in order to handle the case when a directory is specified by a URL but the trailing / has been left off. This can cause misleading results when you try to fetch a file whose read permissions make it inaccessible; the FTP code will try to read it, fail with a 550 error, and then perform a directory listing for the unreadable file. If fine-grained control is needed, consider using the :mod:`ftplib` module, subclassing :class:`FancyURLopener`, or changing _urlopener to meet your needs.

:mod:`urllib.response` --- Response classes used by urllib

The :mod:`urllib.response` module defines functions and classes which define a minimal file like interface, including read() and readline(). The typical response object is an addinfourl instance, which defines an info() method and that returns headers and a geturl() method that returns the url. Functions defined by this module are used internally by the :mod:`urllib.request` module.