data may be a string 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
application/x-www-form-urlencoded format. The
urllib.urlencode() function takes a mapping or sequence of 2-tuples and
returns a string in this format.

The optional timeout parameter specifies a timeout in seconds for blocking
operations like the connection attempt (if not specified, the global default
timeout setting will be used). This actually only works for HTTP, HTTPS,
FTP and FTPS connections.

This function returns a file-like object with two additional methods:

geturl() — return the URL of the resource retrieved, commonly used to
determine if a redirect was followed

Install an OpenerDirector instance as the default global opener.
Installing an opener is only necessary if you want urlopen to use that opener;
otherwise, simply call OpenerDirector.open() instead of urlopen().
The code does not check for a real OpenerDirector, and any class with
the appropriate interface will work.

Though being an exception (a subclass of URLError), an HTTPError
can also function as a non-exceptional file-like return value (the same thing
that urlopen() returns). This is useful when handling exotic HTTP
errors, such as requests for authentication.

data may be a string 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
application/x-www-form-urlencoded format. The
urllib.urlencode() function takes a mapping or sequence of 2-tuples and
returns a string in this format.

headers should be a dictionary, and will be treated as if 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;Linuxi686)Gecko/20071127Firefox/2.0.0.11", while urllib2‘s
default user agent string is "Python-urllib/2.6" (on Python 2.6).

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 cookielib.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.

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
. If no proxy environment variables are set, 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.

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 HTTPPasswordMgr; refer to section
HTTPPasswordMgr Objects 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 HTTPPasswordMgr; refer to section
HTTPPasswordMgr Objects for information on the interface that must be
supported.

Handle authentication with the proxy. password_mgr, if given, should be
something that is compatible with HTTPPasswordMgr; refer to section
HTTPPasswordMgr Objects 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 HTTPPasswordMgr; refer to section
HTTPPasswordMgr Objects 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 HTTPPasswordMgr; refer to section
HTTPPasswordMgr Objects for information on the interface that must be
supported.

Handle authentication with the proxy. password_mgr, if given, should be
something that is compatible with HTTPPasswordMgr; refer to section
HTTPPasswordMgr Objects for information on the interface that must be
supported.

Add another header to the request. Headers are currently ignored by all
handlers except HTTP handlers, where they are added to the list of headers sent
to the server. Note that there cannot be more than one header with the same
name, and later calls will overwrite previous calls in case the key collides.
Currently, this is no loss of HTTP functionality, since all headers which have
meaning when used more than once have a (header-specific) way of gaining the
same functionality using only one header.

Open the given url (which can be a request object or a string), optionally
passing the given data. Arguments, return values and exceptions raised are
the same as those of urlopen() (which simply calls the open()
method on the currently installed global OpenerDirector). The
optional timeout parameter specifies a timeout in seconds for blocking
operations like the connection attempt (if not specified, the global default
timeout setting will be used). The timeout feature actually works only for
HTTP, HTTPS, FTP and FTPS connections).

Handle an error of the given protocol. This will call the registered error
handlers for the given protocol with the given arguments (which are protocol
specific). The HTTP protocol is a special case which uses the HTTP response
code to determine the specific error handler; refer to the http_error_*()
methods of the handler classes.

Return values and exceptions raised are the same as those of urlopen().

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.

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

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

In fact, the above algorithm is first tried for methods named
default_open(). If all such methods return None, the
algorithm is repeated for methods named like protocol_open. If all
such methods return None, the algorithm is repeated for methods
named unknown_open().

This method is not defined in BaseHandler, but subclasses should
define it if they want to catch all URLs.

This method, if implemented, will be called by the parent
OpenerDirector. It should return a file-like object as described in
the return value of the open() of OpenerDirector, or None.
It should raise URLError, unless a truly exceptional thing happens (for
example, MemoryError should not be mapped to URLError).

This method will be called before any protocol-specific open method.

BaseHandler.protocol_open(req)

(“protocol” is to be replaced by the protocol name.)

This method is not defined in BaseHandler, but subclasses should
define it if they want to handle URLs with the given protocol.

This method, if defined, will be called by the parent OpenerDirector.
Return values should be the same as for default_open().

This method is not defined in BaseHandler, but subclasses should
override it if they intend to provide a catch-all for otherwise unhandled HTTP
errors. It will be called automatically by the OpenerDirector getting
the error, and should not normally be called in other circumstances.

req will be a Request object, fp will be a file-like object with
the HTTP error body, code will be the three-digit code of the error, msg
will be the user-visible explanation of the code and hdrs will be a mapping
object with the headers of the error.

Return values and exceptions raised should be the same as those of
urlopen().

This method is not defined in BaseHandler, but subclasses should
define it if they want to pre-process requests of the given protocol.

This method, if defined, will be called by the parent OpenerDirector.
req will be a Request object. The return value should be a
Request object.

BaseHandler.protocol_response(req, response)

(“protocol” is to be replaced by the protocol name.)

This method is not defined in BaseHandler, but subclasses should
define it if they want to post-process responses of the given protocol.

This method, if defined, will be called by the parent OpenerDirector.
req will be a Request object. response will be an object
implementing the same interface as the return value of urlopen(). The
return value should implement the same interface as the return value of
urlopen().

Return a Request or None in response to a redirect. This is called
by the default implementations of the http_error_30*() methods when a
redirection is received from the server. If a redirection should take place,
return a new Request to allow http_error_30*() to perform the
redirect to newurl. Otherwise, raise HTTPError if no other handler
should try to handle this URL, or return None if you can’t but another
handler might.

Note

The default implementation of this method does not strictly follow RFC 2616,
which says that 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 the default implementation reproduces this behavior.

The ProxyHandler will have a method protocol_open for every
protocol which has a proxy in the proxies dictionary given in the
constructor. The method will modify requests to go through the proxy, by
calling request.set_proxy(), and call the next handler in the chain to
actually execute the protocol.

uri can be either a single URI, or a sequence of URIs. realm, user and
passwd must be strings. This causes (user,passwd) to be used as
authentication tokens when authentication for realm and a super-URI of any of
the given URIs is given.

Handle an authentication request by getting a user/password pair, and re-trying
the request. authreq should be the name of the header where the information
about the realm is included in the request, host specifies the URL and path to
authenticate for, req should be the (failed) Request object, and
headers should be the error headers.

host is either an authority (e.g. "python.org") or a URL containing an
authority component (e.g. "http://python.org/"). In either case, the
authority must not contain a userinfo component (so, "python.org" and
"python.org:80" are fine, "joe:password@python.org" is not).

authreq should be the name of the header where the information about the realm
is included in the request, host should be the host to authenticate to, req
should be the (failed) Request object, and headers should be the
error headers.

Here 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.

>>> importurllib2>>> req=urllib2.Request(url='https://localhost/cgi-bin/test.cgi',... data='This data is passed to stdin of the CGI')>>> f=urllib2.urlopen(req)>>> printf.read()Got Data: "This data is passed to stdin of the CGI"

importurllib2# Create an OpenerDirector with support for Basic HTTP Authentication...auth_handler=urllib2.HTTPBasicAuthHandler()auth_handler.add_password(realm='PDQ Application',uri='https://mahler:8092/site-updates.py',user='klem',passwd='kadidd!ehopper')opener=urllib2.build_opener(auth_handler)# ...and install it globally so it can be used with urlopen.urllib2.install_opener(opener)urllib2.urlopen('http://www.example.com/login.html')

build_opener() provides many handlers by default, including a
ProxyHandler. By default, ProxyHandler uses the environment
variables named <scheme>_proxy, where <scheme> is the URL scheme
involved. For example, the http_proxy environment variable is read to
obtain the HTTP proxy’s URL.

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

proxy_handler=urllib2.ProxyHandler({'http':'http://www.example.com:3128/'})proxy_auth_handler=urllib2.ProxyBasicAuthHandler()proxy_auth_handler.add_password('realm','host','username','password')opener=urllib2.build_opener(proxy_handler,proxy_auth_handler)# This time, rather than install the OpenerDirector, we use it directly:opener.open('http://www.example.com/login.html')