cpython: c499cc2c4a06 Doc/library/urllib.request.rst (original) (raw)
Issue #22098: ctypes' BigEndianStructure and LittleEndianStructure now define an empty __slots__ so that subclasses don't always get an instance dict. Patch by Claudiu Popa. [#22098]
line wrap: on
line source
:mod:urllib.request
--- Extensible library for opening URLs
=============================================================
.. module:: urllib.request
:synopsis: Extensible library for opening URLs.
.. moduleauthor:: Jeremy Hylton jeremy@alum.mit.edu
.. sectionauthor:: Moshe Zadka moshez@users.sourceforge.net
.. sectionauthor:: Senthil Kumaran senthil@uthcode.com
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:
.. function:: urlopen(url, data=None[, timeout], *, cafile=None, capath=None, cadefault=False)
Open the URL url, which can be either a string or a
:class:Request
object.
data must be a bytes object specifying additional data to be sent to the
server, or None
if no such data is needed. data may also be an
iterable object and in that case Content-Length value must be specified in
the headers. 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
.
urllib.request module uses HTTP/1.1 and includes Connection:close
header
in its HTTP requests.
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 and FTP connections.
The optional cafile and capath parameters specify a set of trusted
CA certificates for HTTPS requests. cafile should point to a single
file containing a bundle of CA certificates, whereas capath should
point to a directory of hashed certificate files. More information can
be found in :meth:ssl.SSLContext.load_verify_locations
.
The cadefault parameter specifies whether to fall back to loading a
default certificate store defined by the underlying OpenSSL library if the
cafile and capath parameters are omitted. This will only work on
some non-Windows platforms.
.. warning::
If neither cafile nor capath is specified, and cadefault is False
,
an HTTPS request will not do any verification of the server's
certificate.
For http and https urls, this function returns a
:class:http.client.HTTPResponse
object which has the following
:ref:httpresponse-objects
methods.
For ftp, file, and data urls and requests explicitly handled by legacy
:class:URLopener
and :class:FancyURLopener
classes, this function
returns a :class:urllib.response.addinfourl
object which can work as
:term:context manager
and has methods such as
- :meth:
~urllib.response.addinfourl.geturl
--- return the URL of the resource retrieved, commonly used to determine if a redirect was followed - :meth:
~urllib.response.addinfourl.info
--- return the meta-information of the page, such as headers, in the form of an :func:email.message_from_string
instance (seeQuick Reference to HTTP Headers <http://www.cs.tut.fi/~jkorpela/http.html>
_) - :meth:
~urllib.response.addinfourl.getcode
-- return the HTTP status code of the response. Raises :exc:~urllib.error.URLError
on errors. Note thatNone
may be returned if no handler handles the request (though the default installed global :class:OpenerDirector
uses :class:UnknownHandler
to ensure this never happens). In addition, if proxy settings are detected (for example, when a*_proxy
environment variable like :envvar:http_proxy
is set), :class:ProxyHandler
is default installed and makes sure the requests are handled through the proxy. The legacyurllib.urlopen
function from Python 2.6 and earlier has been discontinued; :func:urllib.request.urlopen
corresponds to the oldurllib2.urlopen
. Proxy handling, which was done by passing a dictionary parameter tourllib.urlopen
, can be obtained by using :class:ProxyHandler
objects. .. versionchanged:: 3.2 cafile and capath were added. .. versionchanged:: 3.2 HTTPS virtual hosts are now supported if possible (that is, if :data:ssl.HAS_SNI
is true). .. versionadded:: 3.2 data can be an iterable object. .. versionchanged:: 3.3 cadefault was added. .. function:: install_opener(opener) Install an :class:OpenerDirector
instance as the default global opener. Installing an opener is only necessary if you want urlopen to use that opener; otherwise, simply call :meth:OpenerDirector.open
instead of :func:~urllib.request.urlopen
. The code does not check for a real :class:OpenerDirector
, and any class with the appropriate interface will work. .. function:: build_opener([handler, ...]) Return an :class:OpenerDirector
instance, which chains the handlers in the order given. handler\s can be either instances of :class:BaseHandler
, or subclasses of :class:BaseHandler
(in which case it must be possible to call the constructor without any parameters). Instances of the following classes will be in front of the handler\s, unless the handler\s contain them, instances of them or subclasses of them: :class:ProxyHandler
(if proxy settings are detected), :class:UnknownHandler
, :class:HTTPHandler
, :class:HTTPDefaultErrorHandler
, :class:HTTPRedirectHandler
, :class:FTPHandler
, :class:FileHandler
, :class:HTTPErrorProcessor
. If the Python installation has SSL support (i.e., if the :mod:ssl
module can be imported), :class:HTTPSHandler
will also be added. A :class:BaseHandler
subclass may also change its :attr:handler_order
attribute to modify its position in the handlers list. .. function:: pathname2url(path) Convert the pathname path from the local syntax for a path to the form used in the path component of a URL. This does not produce a complete URL. The return value will already be quoted using the :func:~urllib.parse.quote
function. .. function:: url2pathname(path) Convert the path component path from a percent-encoded URL to the local syntax for a path. This does not accept a complete URL. This function uses :func:~urllib.parse.unquote
to decode path. .. function:: getproxies() This helper function returns a dictionary of scheme to proxy server URL mappings. It scans the environment for variables named<scheme>_proxy
, in a case insensitive approach, for all operating systems first, and when it cannot find it, looks for proxy information from Mac OSX System Configuration for Mac OS X and Windows Systems Registry for Windows. The following classes are provided: .. class:: Request(url, data=None, headers={}, origin_req_host=None, unverifiable=False, method=None) 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, orNone
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 inContent-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 inContent-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" theUser-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[](#l194) (X11; U; Linux i686) Gecko/20071127 Firefox/2.0.0.11"
, while :mod:urllib
's default user agent string is"Python-urllib/2.6"
(on Python 2.6). An example of usingContent-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 tohttp.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 toFalse
. 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'
). If provided, its value is stored in the :attr:~Request.method
attribute and is used by :meth:get_method()
. Subclasses may indicate a default method by setting the :attr:~Request.method
attribute in the class itself. .. versionchanged:: 3.3 :attr:Request.method
argument is added to the Request class. .. versionchanged:: 3.4 Default :attr:Request.method
may be indicated at the class level. .. class:: OpenerDirector() The :class:OpenerDirector
class opens URLs via :class:BaseHandler
\ s chained together. It manages the chaining of handlers, and recovery from errors. .. class:: BaseHandler() This is the base class for all registered handlers --- and handles only the simple mechanics of registration. .. class:: HTTPDefaultErrorHandler() A class which defines a default handler for HTTP error responses; all responses are turned into :exc:~urllib.error.HTTPError
exceptions. .. class:: HTTPRedirectHandler() A class to handle redirections. .. class:: HTTPCookieProcessor(cookiejar=None) A class to handle HTTP Cookies. .. class:: ProxyHandler(proxies=None) 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. .. class:: HTTPPasswordMgr() Keep a database of(realm, uri) -> (user, password)
mappings. .. class:: HTTPPasswordMgrWithDefaultRealm() Keep a database of(realm, uri) -> (user, password)
mappings. A realm ofNone
is considered a catch-all realm, which is searched if no other realm fits. .. class:: AbstractBasicAuthHandler(password_mgr=None) 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. .. class:: HTTPBasicAuthHandler(password_mgr=None) 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. .. class:: ProxyBasicAuthHandler(password_mgr=None) 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. .. class:: AbstractDigestAuthHandler(password_mgr=None) 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. .. class:: HTTPDigestAuthHandler(password_mgr=None) 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. .. versionchanged:: 3.3 Raise :exc:ValueError
on unsupported Authentication Scheme. .. class:: ProxyDigestAuthHandler(password_mgr=None) 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. .. class:: HTTPHandler() A class to handle opening of HTTP URLs. .. class:: HTTPSHandler(debuglevel=0, context=None, check_hostname=None) A class to handle opening of HTTPS URLs. context and check_hostname have the same meaning as in :class:http.client.HTTPSConnection
. .. versionchanged:: 3.2 context and check_hostname were added. .. class:: FileHandler() Open local files. .. class:: DataHandler() Open data URLs. .. versionadded:: 3.4 .. class:: FTPHandler() Open FTP URLs. .. class:: CacheFTPHandler() Open FTP URLs, keeping a cache of open FTP connections to minimize delays. .. class:: UnknownHandler() A catch-all class to handle unknown URLs. .. class:: HTTPErrorProcessor() Process HTTP error responses. .. _request-objects: 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. .. attribute:: Request.full_url The original URL passed to the constructor. .. versionchanged:: 3.4 Request.full_url is a property with setter, getter and a deleter. Getting :attr:~Request.full_url
returns the original request URL with the fragment, if it was present. .. attribute:: Request.type The URI scheme. .. attribute:: Request.host The URI authority, typically a host, but may also contain a port separated by a colon. .. attribute:: Request.origin_req_host The original host for the request, without port. .. attribute:: Request.selector The URI path. If the :class:Request
uses a proxy, then selector will be the full url that is passed to the proxy. .. attribute:: Request.data The entity body for the request, or None if not specified. .. versionchanged:: 3.4 Changing value of :attr:Request.data
now deletes "Content-Length" header if it was previously set or calculated. .. attribute:: Request.unverifiable boolean, indicates whether the request is unverifiable as defined by RFC 2965. .. attribute:: Request.method The HTTP request method to use. By default its value is :const:None
, which means that :meth:~Request.get_method
will do its normal computation of the method to be used. Its value can be set (thus overriding the default computation in :meth:~Request.get_method
) either by providing a default value by setting it at the class level in a :class:Request
subclass, or by passing a value in to the :class:Request
constructor via the method argument. .. versionadded:: 3.3 .. versionchanged:: 3.4 A default value can now be set in subclasses; previously it could only be set via the constructor argument. .. method:: Request.get_method() Return a string indicating the HTTP request method. If :attr:Request.method
is notNone
, return its value, otherwise return'GET'
if :attr:Request.data
isNone
, or'POST'
if it's not. This is only meaningful for HTTP requests. .. versionchanged:: 3.3 get_method now looks at the value of :attr:Request.method
. .. method:: Request.add_header(key, val) 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. .. method:: Request.add_unredirected_header(key, header) Add a header that will not be added to a redirected request. .. method:: Request.has_header(header) Return whether the instance has the named header (checks both regular and unredirected). .. method:: Request.remove_header(header) Remove named header from the request instance (both from regular and unredirected headers). .. versionadded:: 3.4 .. method:: Request.get_full_url() Return the URL given in the constructor. .. versionchanged:: 3.4 Returns :attr:Request.full_url
.. method:: Request.set_proxy(host, type) Prepare the request by connecting to a proxy server. The host and type will replace those of the instance, and the instance's selector will be the original URL given in the constructor. .. method:: Request.get_header(header_name, default=None) Return the value of the given header. If the header is not present, return the default value. .. method:: Request.header_items() Return a list of tuples (header_name, header_value) of the Request headers. .. versionchanged:: 3.4 The request methods add_data, has_data, get_data, get_type, get_host, get_selector, get_origin_req_host and is_unverifiable that were deprecated since 3.3 have been removed. .. _opener-director-objects: OpenerDirector Objects ---------------------- :class:OpenerDirector
instances have the following methods: .. method:: OpenerDirector.add_handler(handler) handler should be an instance of :class:BaseHandler
. The following methods are searched, and added to the possible chains (note that HTTP errors are a special case). - :meth:
protocol_open
--- signal that the handler knows how to open protocol URLs. - :meth:
http_error_type
--- signal that the handler knows how to handle HTTP errors with HTTP error code type. - :meth:
protocol_error
--- signal that the handler knows how to handle errors from (non-\http
) protocol. - :meth:
protocol_request
--- signal that the handler knows how to pre-process protocol requests. - :meth:
protocol_response
--- signal that the handler knows how to post-process protocol responses. .. method:: OpenerDirector.open(url, data=None[, timeout]) 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 :func:urlopen
(which simply calls the :meth:open
method on the currently installed global :class: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 and FTP connections). .. method:: OpenerDirector.error(proto, *args) 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 :meth:http_error_\*
methods of the handler classes. Return values and exceptions raised are the same as those of :func: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 :meth:protocol_request
has that
method called to pre-process the request.
#. 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:~urllib.error.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:~OpenerDirector.open
and
:meth:~OpenerDirector.error
methods.
#. Every handler with a method named like :meth:protocol_response
has that
method called to post-process the response.
.. _base-handler-objects:
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:
.. method:: BaseHandler.add_parent(director)
Add a director as parent.
.. method:: BaseHandler.close()
Remove any parents.
The following attribute and methods should only be used by classes derived from
:class:BaseHandler
.
.. note::
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
.
.. attribute:: BaseHandler.parent
A valid :class:OpenerDirector
, which can be used to open using a different
protocol, or handle errors.
.. method:: BaseHandler.default_open(req)
This method is not defined in :class:BaseHandler
, but subclasses should
define it if they want to catch all URLs.
This method, if implemented, will be called by the parent
:class:OpenerDirector
. It should return a file-like object as described in
the return value of the :meth:open
of :class:OpenerDirector
, or None
.
It should raise :exc:~urllib.error.URLError
, unless a truly exceptional
thing happens (for example, :exc:MemoryError
should not be mapped to
:exc:URLError
).
This method will be called before any protocol-specific open method.
.. method:: BaseHandler.protocol_open(req)
:noindex:
This method is not defined in :class: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 :class:OpenerDirector
.
Return values should be the same as for :meth:default_open
.
.. method:: BaseHandler.unknown_open(req)
This method is not defined in :class:BaseHandler
, but subclasses should
define it if they want to catch all URLs with no specific registered handler to
open it.
This method, if implemented, will be called by the :attr:parent
:class:OpenerDirector
. Return values should be the same as for
:meth:default_open
.
.. method:: BaseHandler.http_error_default(req, fp, code, msg, hdrs)
This method is not defined in :class: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 :class:OpenerDirector
getting
the error, and should not normally be called in other circumstances.
req will be a :class: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
:func:urlopen
.
.. method:: BaseHandler.http_error_nnn(req, fp, code, msg, hdrs)
nnn should be a three-digit HTTP error code. This method is also not defined
in :class:BaseHandler
, but will be called, if it exists, on an instance of a
subclass, when an HTTP error with code nnn occurs.
Subclasses should override this method to handle specific HTTP errors.
Arguments, return values and exceptions raised should be the same as for
:meth:http_error_default
.
.. method:: BaseHandler.protocol_request(req)
:noindex:
This method is not defined in :class: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 :class:OpenerDirector
.
req will be a :class:Request
object. The return value should be a
:class:Request
object.
.. method:: BaseHandler.protocol_response(req, response)
:noindex:
This method is not defined in :class: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 :class:OpenerDirector
.
req will be a :class:Request
object. response will be an object
implementing the same interface as the return value of :func:urlopen
. The
return value should implement the same interface as the return value of
:func:urlopen
.
.. _http-redirect-handler:
HTTPRedirectHandler Objects
---------------------------
.. note::
Some HTTP redirections require action from this module's client code. If this
is the case, :exc:~urllib.error.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.
.. method:: HTTPRedirectHandler.redirect_request(req, fp, code, msg, hdrs, newurl)
Return a :class:Request
or None
in response to a redirect. This is called
by the default implementations of the :meth:http_error_30\*
methods when a
redirection is received from the server. If a redirection should take place,
return a new :class:Request
to allow :meth:http_error_30\*
to perform the
redirect to newurl. Otherwise, raise :exc:~urllib.error.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.
.. method:: HTTPRedirectHandler.http_error_301(req, fp, code, msg, hdrs)
Redirect to the Location:
or URI:
URL. This method is called by the
parent :class:OpenerDirector
when getting an HTTP 'moved permanently' response.
.. method:: HTTPRedirectHandler.http_error_302(req, fp, code, msg, hdrs)
The same as :meth:http_error_301
, but called for the 'found' response.
.. method:: HTTPRedirectHandler.http_error_303(req, fp, code, msg, hdrs)
The same as :meth:http_error_301
, but called for the 'see other' response.
.. method:: HTTPRedirectHandler.http_error_307(req, fp, code, msg, hdrs)
The same as :meth:http_error_301
, but called for the 'temporary redirect'
response.
.. _http-cookie-processor:
HTTPCookieProcessor Objects
---------------------------
:class:HTTPCookieProcessor
instances have one attribute:
.. attribute:: HTTPCookieProcessor.cookiejar
The :class:http.cookiejar.CookieJar
in which cookies are stored.
.. _proxy-handler:
ProxyHandler Objects
--------------------
.. method:: ProxyHandler.protocol_open(request)
:noindex:
The :class:ProxyHandler
will have a method :meth: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.
.. _http-password-mgr:
HTTPPasswordMgr Objects
-----------------------
These methods are available on :class:HTTPPasswordMgr
and
:class:HTTPPasswordMgrWithDefaultRealm
objects.
.. method:: HTTPPasswordMgr.add_password(realm, uri, user, passwd)
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.
.. method:: HTTPPasswordMgr.find_user_password(realm, authuri)
Get user/password for given realm and URI, if any. This method will return
(None, None)
if there is no matching user/password.
For :class:HTTPPasswordMgrWithDefaultRealm
objects, the realm None
will be
searched if the given realm has no matching user/password.
.. _abstract-basic-auth-handler:
AbstractBasicAuthHandler Objects
--------------------------------
.. method:: AbstractBasicAuthHandler.http_error_auth_reqed(authreq, host, req, headers)
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) :class: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).
.. _http-basic-auth-handler:
HTTPBasicAuthHandler Objects
----------------------------
.. method:: HTTPBasicAuthHandler.http_error_401(req, fp, code, msg, hdrs)
Retry the request with authentication information, if available.
.. _proxy-basic-auth-handler:
ProxyBasicAuthHandler Objects
-----------------------------
.. method:: ProxyBasicAuthHandler.http_error_407(req, fp, code, msg, hdrs)
Retry the request with authentication information, if available.
.. _abstract-digest-auth-handler:
AbstractDigestAuthHandler Objects
---------------------------------
.. method:: AbstractDigestAuthHandler.http_error_auth_reqed(authreq, host, req, headers)
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) :class:Request
object, and headers should be the
error headers.
.. _http-digest-auth-handler:
HTTPDigestAuthHandler Objects
-----------------------------
.. method:: HTTPDigestAuthHandler.http_error_401(req, fp, code, msg, hdrs)
Retry the request with authentication information, if available.
.. _proxy-digest-auth-handler:
ProxyDigestAuthHandler Objects
------------------------------
.. method:: ProxyDigestAuthHandler.http_error_407(req, fp, code, msg, hdrs)
Retry the request with authentication information, if available.
.. _http-handler-objects:
HTTPHandler Objects
-------------------
.. method:: HTTPHandler.http_open(req)
Send an HTTP request, which can be either GET or POST, depending on
req.has_data()
.
.. _https-handler-objects:
HTTPSHandler Objects
--------------------
.. method:: HTTPSHandler.https_open(req)
Send an HTTPS request, which can be either GET or POST, depending on
req.has_data()
.
.. _file-handler-objects:
FileHandler Objects
-------------------
.. method:: FileHandler.file_open(req)
Open the file locally, if there is no host name, or the host name is
'localhost'
.
.. versionchanged:: 3.2
This method is applicable only for local hostnames. When a remote
hostname is given, an :exc:~urllib.error.URLError
is raised.
.. _data-handler-objects:
DataHandler Objects
-------------------
.. method:: DataHandler.data_open(req)
Read a data URL. This kind of URL contains the content encoded in the URL
itself. The data URL syntax is specified in :rfc:2397
. This implementation
ignores white spaces in base64 encoded data URLs so the URL may be wrapped
in whatever source file it comes from. But even though some browsers don't
mind about a missing padding at the end of a base64 encoded data URL, this
implementation will raise an :exc:ValueError
in that case.
.. _ftp-handler-objects:
FTPHandler Objects
------------------
.. method:: FTPHandler.ftp_open(req)
Open the FTP file indicated by req. The login is always done with empty
username and password.
.. _cacheftp-handler-objects:
CacheFTPHandler Objects
-----------------------
:class:CacheFTPHandler
objects are :class:FTPHandler
objects with the
following additional methods:
.. method:: CacheFTPHandler.setTimeout(t)
Set timeout of connections to t seconds.
.. method:: CacheFTPHandler.setMaxConns(m)
Set maximum number of cached connections to m.
.. _unknown-handler-objects:
UnknownHandler Objects
----------------------
.. method:: UnknownHandler.unknown_open()
Raise a :exc:~urllib.error.URLError
exception.
.. _http-error-processor-objects:
HTTPErrorProcessor Objects
--------------------------
.. method:: HTTPErrorProcessor.http_response()
Process HTTP error responses.
For 200 error codes, the response object is returned immediately.
For non-200 error codes, this simply passes the job on to the
:meth:protocol_error_code
handler methods, via :meth:OpenerDirector.error
.
Eventually, :class:HTTPDefaultErrorHandler
will raise an
:exc:~urllib.error.HTTPError
if no other handler handles the error.
.. method:: HTTPErrorProcessor.https_response()
Process HTTPS error responses.
The behavior is same as :meth:http_response
.
.. _urllib-request-examples:
Examples
--------
This example gets the python.org main page and displays the first 300 bytes of
it. ::
import urllib.request f = urllib.request.urlopen('http://www.python.org/')[](#l1052) print(f.read(300)) b'\n\n\n<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">\n\n\n \n Python Programming '<a href="#l1058" title="null"></a> <a href="#l1059" title="null"></a> Note that urlopen returns a bytes object. This is because there is no way<a href="#l1060" title="null"></a> for urlopen to automatically determine the encoding of the byte stream<a href="#l1061" title="null"></a> it receives from the http server. In general, a program will decode<a href="#l1062" title="null"></a> the returned bytes object to string once it determines or guesses<a href="#l1063" title="null"></a> the appropriate encoding.<a href="#l1064" title="null"></a> <a href="#l1065" title="null"></a> The following W3C document, <a href="http://www.w3.org/International/O-charset\" title="undefined" rel="noopener noreferrer">http://www.w3.org/International/O-charset\</a> , lists<a href="#l1066" title="null"></a> the various ways in which a (X)HTML or a XML document could have specified its<a href="#l1067" title="null"></a> encoding information.<a href="#l1068" title="null"></a> <a href="#l1069" title="null"></a> As the python.org website uses <em>utf-8</em> encoding as specified in its meta tag, we<a href="#l1070" title="null"></a> will use the same for decoding the bytes object. ::<a href="#l1071" title="null"></a> <a href="#l1072" title="null"></a> with urllib.request.urlopen('<a href="http://www.python.org/" title="undefined" rel="noopener noreferrer">http://www.python.org/</a>') as f:<a href="#l1073" title="null"></a> ... print(f.read(100).decode('utf-8'))<a href="#l1074" title="null"></a> ...<a href="#l1075" title="null"></a> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"<a href="#l1076" title="null"></a> "<a href="http://www.w3.org/TR/xhtml1/DTD/xhtm[](#l1077)" title="undefined" rel="noopener noreferrer">http://www.w3.org/TR/xhtml1/DTD/xhtm[](#l1077)</a> <a href="#l1078" title="null"></a> It is also possible to achieve the same result without using the<a href="#l1079" title="null"></a> :term:<code>context manager</code> approach. ::<a href="#l1080" title="null"></a> <a href="#l1081" title="null"></a> import urllib.request<a href="#l1082" title="null"></a> f = urllib.request.urlopen('<a href="http://www.python.org/')[](#l1083)" title="undefined" rel="noopener noreferrer">http://www.python.org/')[](#l1083)</a> print(f.read(100).decode('utf-8'))<a href="#l1084" title="null"></a> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"<a href="#l1085" title="null"></a> "<a href="http://www.w3.org/TR/xhtml1/DTD/xhtm[](#l1086)" title="undefined" rel="noopener noreferrer">http://www.w3.org/TR/xhtml1/DTD/xhtm[](#l1086)</a> <a href="#l1087" title="null"></a> In the following example, we are sending a data-stream to the stdin of a CGI<a href="#l1088" title="null"></a> and reading the data it returns to us. Note that this example will only work<a href="#l1089" title="null"></a> when the Python installation supports SSL. ::<a href="#l1090" title="null"></a> <a href="#l1091" title="null"></a> import urllib.request<a href="#l1092" title="null"></a> req = urllib.request.Request(url='<a href="https://localhost/cgi-bin/test.cgi',[](#l1093)" title="undefined" rel="noopener noreferrer">https://localhost/cgi-bin/test.cgi',[](#l1093)</a> ... data=b'This data is passed to stdin of the CGI')<a href="#l1094" title="null"></a> f = urllib.request.urlopen(req)<a href="#l1095" title="null"></a> print(f.read().decode('utf-8'))<a href="#l1096" title="null"></a> Got Data: "This data is passed to stdin of the CGI"<a href="#l1097" title="null"></a> <a href="#l1098" title="null"></a> The code for the sample CGI used in the above example is::<a href="#l1099" title="null"></a> <a href="#l1100" title="null"></a> #!/usr/bin/env python<a href="#l1101" title="null"></a> import sys<a href="#l1102" title="null"></a> data = sys.stdin.read()<a href="#l1103" title="null"></a> print('Content-type: text-plain\n\nGot Data: "%s"' % data)<a href="#l1104" title="null"></a> <a href="#l1105" title="null"></a> Here is an example of doing a <code>PUT</code> request using :class:<code>Request</code>::<a href="#l1106" title="null"></a> <a href="#l1107" title="null"></a> import urllib.request<a href="#l1108" title="null"></a> DATA=b'some data'<a href="#l1109" title="null"></a> req = urllib.request.Request(url='<a href="http://localhost:8080" title="undefined" rel="noopener noreferrer">http://localhost:8080</a>', data=DATA,method='PUT')<a href="#l1110" title="null"></a> f = urllib.request.urlopen(req)<a href="#l1111" title="null"></a> print(f.status)<a href="#l1112" title="null"></a> print(f.reason)<a href="#l1113" title="null"></a> <a href="#l1114" title="null"></a> Use of Basic HTTP Authentication::<a href="#l1115" title="null"></a> <a href="#l1116" title="null"></a> import urllib.request<a href="#l1117" title="null"></a></p> </blockquote> </blockquote> </blockquote> <h1 id="create-an-openerdirector-with-support-for-basic-http-authentication"><a class="anchor" aria-hidden="true" tabindex="-1" href="#create-an-openerdirector-with-support-for-basic-http-authentication"><svg class="octicon octicon-link" viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M7.775 3.275a.75.75 0 001.06 1.06l1.25-1.25a2 2 0 112.83 2.83l-2.5 2.5a2 2 0 01-2.83 0 .75.75 0 00-1.06 1.06 3.5 3.5 0 004.95 0l2.5-2.5a3.5 3.5 0 00-4.95-4.95l-1.25 1.25zm-4.69 9.64a2 2 0 010-2.83l2.5-2.5a2 2 0 012.83 0 .75.75 0 001.06-1.06 3.5 3.5 0 00-4.95 0l-2.5 2.5a3.5 3.5 0 004.95 4.95l1.25-1.25a.75.75 0 00-1.06-1.06l-1.25 1.25a2 2 0 01-2.83 0z"></path></svg></a>Create an OpenerDirector with support for Basic HTTP Authentication...<a href="#l1118" title="null"></a></h1><p> auth_handler = urllib.request.HTTPBasicAuthHandler()<a href="#l1119" title="null"></a> auth_handler.add_password(realm='PDQ Application',<a href="#l1120" title="null"></a> uri='<a href="https://mahler:8092/site-updates.py',[](#l1121)" title="undefined" rel="noopener noreferrer">https://mahler:8092/site-updates.py',[](#l1121)</a> user='klem',<a href="#l1122" title="null"></a> passwd='kadidd!ehopper')<a href="#l1123" title="null"></a> opener = urllib.request.build_opener(auth_handler)<a href="#l1124" title="null"></a></p> <h1 id="and-install-it-globally-so-it-can-be-used-with-urlopen"><a class="anchor" aria-hidden="true" tabindex="-1" href="#and-install-it-globally-so-it-can-be-used-with-urlopen"><svg class="octicon octicon-link" viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M7.775 3.275a.75.75 0 001.06 1.06l1.25-1.25a2 2 0 112.83 2.83l-2.5 2.5a2 2 0 01-2.83 0 .75.75 0 00-1.06 1.06 3.5 3.5 0 004.95 0l2.5-2.5a3.5 3.5 0 00-4.95-4.95l-1.25 1.25zm-4.69 9.64a2 2 0 010-2.83l2.5-2.5a2 2 0 012.83 0 .75.75 0 001.06-1.06 3.5 3.5 0 00-4.95 0l-2.5 2.5a3.5 3.5 0 004.95 4.95l1.25-1.25a.75.75 0 00-1.06-1.06l-1.25 1.25a2 2 0 01-2.83 0z"></path></svg></a>...and install it globally so it can be used with urlopen.<a href="#l1125" title="null"></a></h1><p> urllib.request.install_opener(opener)<a href="#l1126" title="null"></a> urllib.request.urlopen('<a href="http://www.example.com/login.html')[](#l1127)" title="undefined" rel="noopener noreferrer">http://www.example.com/login.html')[](#l1127)</a> <a href="#l1128" title="null"></a> :func:<code>build_opener</code> provides many handlers by default, including a<a href="#l1129" title="null"></a> :class:<code>ProxyHandler</code>. By default, :class:<code>ProxyHandler</code> uses the environment<a href="#l1130" title="null"></a> variables named <code><scheme>_proxy</code>, where <code><scheme></code> is the URL scheme<a href="#l1131" title="null"></a> involved. For example, the :envvar:<code>http_proxy</code> environment variable is read to<a href="#l1132" title="null"></a> obtain the HTTP proxy's URL.<a href="#l1133" title="null"></a> <a href="#l1134" title="null"></a> This example replaces the default :class:<code>ProxyHandler</code> with one that uses<a href="#l1135" title="null"></a> programmatically-supplied proxy URLs, and adds proxy authorization support with<a href="#l1136" title="null"></a> :class:<code>ProxyBasicAuthHandler</code>. ::<a href="#l1137" title="null"></a> <a href="#l1138" title="null"></a> proxy_handler = urllib.request.ProxyHandler({'http': '<a href="http://www.example.com:3128/'})[](#l1139)" title="undefined" rel="noopener noreferrer">http://www.example.com:3128/'})[](#l1139)</a> proxy_auth_handler = urllib.request.ProxyBasicAuthHandler()<a href="#l1140" title="null"></a> proxy_auth_handler.add_password('realm', 'host', 'username', 'password')<a href="#l1141" title="null"></a> <a href="#l1142" title="null"></a> opener = urllib.request.build_opener(proxy_handler, proxy_auth_handler)<a href="#l1143" title="null"></a></p> <h1 id="this-time-rather-than-install-the-openerdirector-we-use-it-directly"><a class="anchor" aria-hidden="true" tabindex="-1" href="#this-time-rather-than-install-the-openerdirector-we-use-it-directly"><svg class="octicon octicon-link" viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M7.775 3.275a.75.75 0 001.06 1.06l1.25-1.25a2 2 0 112.83 2.83l-2.5 2.5a2 2 0 01-2.83 0 .75.75 0 00-1.06 1.06 3.5 3.5 0 004.95 0l2.5-2.5a3.5 3.5 0 00-4.95-4.95l-1.25 1.25zm-4.69 9.64a2 2 0 010-2.83l2.5-2.5a2 2 0 012.83 0 .75.75 0 001.06-1.06 3.5 3.5 0 00-4.95 0l-2.5 2.5a3.5 3.5 0 004.95 4.95l1.25-1.25a.75.75 0 00-1.06-1.06l-1.25 1.25a2 2 0 01-2.83 0z"></path></svg></a>This time, rather than install the OpenerDirector, we use it directly:<a href="#l1144" title="null"></a></h1><p> opener.open('<a href="http://www.example.com/login.html')[](#l1145)" title="undefined" rel="noopener noreferrer">http://www.example.com/login.html')[](#l1145)</a> <a href="#l1146" title="null"></a> Adding HTTP headers:<a href="#l1147" title="null"></a> <a href="#l1148" title="null"></a> Use the <em>headers</em> argument to the :class:<code>Request</code> constructor, or::<a href="#l1149" title="null"></a> <a href="#l1150" title="null"></a> import urllib.request<a href="#l1151" title="null"></a> req = urllib.request.Request('<a href="http://www.example.com/')[](#l1152)" title="undefined" rel="noopener noreferrer">http://www.example.com/')[](#l1152)</a> req.add_header('Referer', '<a href="http://www.python.org/')[](#l1153)" title="undefined" rel="noopener noreferrer">http://www.python.org/')[](#l1153)</a> r = urllib.request.urlopen(req)<a href="#l1154" title="null"></a> <a href="#l1155" title="null"></a> :class:<code>OpenerDirector</code> automatically adds a :mailheader:<code>User-Agent</code> header to<a href="#l1156" title="null"></a> every :class:<code>Request</code>. To change this::<a href="#l1157" title="null"></a> <a href="#l1158" title="null"></a> import urllib.request<a href="#l1159" title="null"></a> opener = urllib.request.build_opener()<a href="#l1160" title="null"></a> opener.addheaders = [('User-agent', 'Mozilla/5.0')]<a href="#l1161" title="null"></a> opener.open('<a href="http://www.example.com/')[](#l1162)" title="undefined" rel="noopener noreferrer">http://www.example.com/')[](#l1162)</a> <a href="#l1163" title="null"></a> Also, remember that a few standard headers (:mailheader:<code>Content-Length</code>,<a href="#l1164" title="null"></a> :mailheader:<code>Content-Type</code> without charset parameter and :mailheader:<code>Host</code>)<a href="#l1165" title="null"></a> are added when the :class:<code>Request</code> is passed to :func:<code>urlopen</code> (or<a href="#l1166" title="null"></a> :meth:<code>OpenerDirector.open</code>).<a href="#l1167" title="null"></a> <a href="#l1168" title="null"></a> .. _urllib-examples:<a href="#l1169" title="null"></a> <a href="#l1170" title="null"></a> Here is an example session that uses the <code>GET</code> method to retrieve a URL<a href="#l1171" title="null"></a> containing parameters::<a href="#l1172" title="null"></a> <a href="#l1173" title="null"></a></p> <blockquote> <blockquote> <blockquote> <p>import urllib.request<a href="#l1174" title="null"></a> import urllib.parse<a href="#l1175" title="null"></a> params = urllib.parse.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0})<a href="#l1176" title="null"></a> f = urllib.request.urlopen("<a href="http://www.musi-cal.com/cgi-bin/query?%s" title="undefined" rel="noopener noreferrer">http://www.musi-cal.com/cgi-bin/query?%s</a>" % params)<a href="#l1177" title="null"></a> print(f.read().decode('utf-8'))<a href="#l1178" title="null"></a> <a href="#l1179" title="null"></a> The following example uses the <code>POST</code> method instead. Note that params output<a href="#l1180" title="null"></a> from urlencode is encoded to bytes before it is sent to urlopen as data::<a href="#l1181" title="null"></a> <a href="#l1182" title="null"></a> import urllib.request<a href="#l1183" title="null"></a> import urllib.parse<a href="#l1184" title="null"></a> data = urllib.parse.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0})<a href="#l1185" title="null"></a> data = data.encode('utf-8')<a href="#l1186" title="null"></a> request = urllib.request.Request("<a href="http://requestb.in/xrbl82xr")[](#l1187)" title="undefined" rel="noopener noreferrer">http://requestb.in/xrbl82xr")[](#l1187)</a></p> <h1 id="adding-charset-parameter-to-the-content-type-header"><a class="anchor" aria-hidden="true" tabindex="-1" href="#adding-charset-parameter-to-the-content-type-header"><svg class="octicon octicon-link" viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M7.775 3.275a.75.75 0 001.06 1.06l1.25-1.25a2 2 0 112.83 2.83l-2.5 2.5a2 2 0 01-2.83 0 .75.75 0 00-1.06 1.06 3.5 3.5 0 004.95 0l2.5-2.5a3.5 3.5 0 00-4.95-4.95l-1.25 1.25zm-4.69 9.64a2 2 0 010-2.83l2.5-2.5a2 2 0 012.83 0 .75.75 0 001.06-1.06 3.5 3.5 0 00-4.95 0l-2.5 2.5a3.5 3.5 0 004.95 4.95l1.25-1.25a.75.75 0 00-1.06-1.06l-1.25 1.25a2 2 0 01-2.83 0z"></path></svg></a>adding charset parameter to the Content-Type header.<a href="#l1188" title="null"></a></h1><p>request.add_header("Content-Type","application/x-www-form-urlencoded;charset=utf-8")<a href="#l1189" title="null"></a> f = urllib.request.urlopen(request, data)<a href="#l1190" title="null"></a> print(f.read().decode('utf-8'))<a href="#l1191" title="null"></a> <a href="#l1192" title="null"></a> The following example uses an explicitly specified HTTP proxy, overriding<a href="#l1193" title="null"></a> environment settings::<a href="#l1194" title="null"></a> <a href="#l1195" title="null"></a> import urllib.request<a href="#l1196" title="null"></a> proxies = {'http': '<a href="http://proxy.example.com:8080/'}[](#l1197)" title="undefined" rel="noopener noreferrer">http://proxy.example.com:8080/'}[](#l1197)</a> opener = urllib.request.FancyURLopener(proxies)<a href="#l1198" title="null"></a> f = opener.open("<a href="http://www.python.org")[](#l1199)" title="undefined" rel="noopener noreferrer">http://www.python.org")[](#l1199)</a> f.read().decode('utf-8')<a href="#l1200" title="null"></a> <a href="#l1201" title="null"></a> The following example uses no proxies at all, overriding environment settings::<a href="#l1202" title="null"></a> <a href="#l1203" title="null"></a> import urllib.request<a href="#l1204" title="null"></a> opener = urllib.request.FancyURLopener({})<a href="#l1205" title="null"></a> f = opener.open("<a href="http://www.python.org/")[](#l1206)" title="undefined" rel="noopener noreferrer">http://www.python.org/")[](#l1206)</a> f.read().decode('utf-8')<a href="#l1207" title="null"></a> <a href="#l1208" title="null"></a> <a href="#l1209" title="null"></a> Legacy interface<a href="#l1210" title="null"></a> ----------------<a href="#l1211" title="null"></a> <a href="#l1212" title="null"></a> The following functions and classes are ported from the Python 2 module<a href="#l1213" title="null"></a> <code>urllib</code> (as opposed to <code>urllib2</code>). They might become deprecated at<a href="#l1214" title="null"></a> some point in the future.<a href="#l1215" title="null"></a> <a href="#l1216" title="null"></a> .. function:: urlretrieve(url, filename=None, reporthook=None, data=None)<a href="#l1217" title="null"></a> <a href="#l1218" title="null"></a> Copy a network object denoted by a URL to a local file. If the URL<a href="#l1219" title="null"></a> points to a local file, the object will not be copied unless filename is supplied.<a href="#l1220" title="null"></a> Return a tuple <code>(filename, headers)</code> where <em>filename</em> is the<a href="#l1221" title="null"></a> local file name under which the object can be found, and <em>headers</em> is whatever<a href="#l1222" title="null"></a> the :meth:<code>info</code> method of the object returned by :func:<code>urlopen</code> returned (for<a href="#l1223" title="null"></a> a remote object). Exceptions are the same as for :func:<code>urlopen</code>.<a href="#l1224" title="null"></a> <a href="#l1225" title="null"></a> The second argument, if present, specifies the file location to copy to (if<a href="#l1226" title="null"></a> absent, the location will be a tempfile with a generated name). The third<a href="#l1227" title="null"></a> argument, if present, is a hook function that will be called once on<a href="#l1228" title="null"></a> establishment of the network connection and once after each block read<a href="#l1229" title="null"></a> thereafter. The hook will be passed three arguments; a count of blocks<a href="#l1230" title="null"></a> transferred so far, a block size in bytes, and the total size of the file. The<a href="#l1231" title="null"></a> third argument may be <code>-1</code> on older FTP servers which do not return a file<a href="#l1232" title="null"></a> size in response to a retrieval request.<a href="#l1233" title="null"></a> <a href="#l1234" title="null"></a> The following example illustrates the most common usage scenario::<a href="#l1235" title="null"></a> <a href="#l1236" title="null"></a> import urllib.request<a href="#l1237" title="null"></a> local_filename, headers = urllib.request.urlretrieve('<a href="http://python.org/')[](#l1238)" title="undefined" rel="noopener noreferrer">http://python.org/')[](#l1238)</a> html = open(local_filename)<a href="#l1239" title="null"></a> html.close()<a href="#l1240" title="null"></a> <a href="#l1241" title="null"></a> If the <em>url</em> uses the :file:<code>http:</code> scheme identifier, the optional <em>data</em><a href="#l1242" title="null"></a> argument may be given to specify a <code>POST</code> request (normally the request<a href="#l1243" title="null"></a> type is <code>GET</code>). The <em>data</em> argument must be a bytes object in standard<a href="#l1244" title="null"></a> :mimetype:<code>application/x-www-form-urlencoded</code> format; see the<a href="#l1245" title="null"></a> :func:<code>urllib.parse.urlencode</code> function.<a href="#l1246" title="null"></a> <a href="#l1247" title="null"></a> :func:<code>urlretrieve</code> will raise :exc:<code>ContentTooShortError</code> when it detects that<a href="#l1248" title="null"></a> the amount of data available was less than the expected amount (which is the<a href="#l1249" title="null"></a> size reported by a <em>Content-Length</em> header). This can occur, for example, when<a href="#l1250" title="null"></a> the download is interrupted.<a href="#l1251" title="null"></a> <a href="#l1252" title="null"></a> The <em>Content-Length</em> is treated as a lower bound: if there's more data to read,<a href="#l1253" title="null"></a> urlretrieve reads more data, but if less data is available, it raises the<a href="#l1254" title="null"></a> exception.<a href="#l1255" title="null"></a> <a href="#l1256" title="null"></a> You can still retrieve the downloaded data in this case, it is stored in the<a href="#l1257" title="null"></a> :attr:<code>content</code> attribute of the exception instance.<a href="#l1258" title="null"></a> <a href="#l1259" title="null"></a> If no <em>Content-Length</em> header was supplied, urlretrieve can not check the size<a href="#l1260" title="null"></a> of the data it has downloaded, and just returns it. In this case you just have<a href="#l1261" title="null"></a> to assume that the download was successful.<a href="#l1262" title="null"></a> <a href="#l1263" title="null"></a> .. function:: urlcleanup()<a href="#l1264" title="null"></a> <a href="#l1265" title="null"></a> Cleans up temporary files that may have been left behind by previous<a href="#l1266" title="null"></a> calls to :func:<code>urlretrieve</code>.<a href="#l1267" title="null"></a> <a href="#l1268" title="null"></a> .. class:: URLopener(proxies=None, **x509)<a href="#l1269" title="null"></a> <a href="#l1270" title="null"></a> .. deprecated:: 3.3<a href="#l1271" title="null"></a> <a href="#l1272" title="null"></a> Base class for opening and reading URLs. Unless you need to support opening<a href="#l1273" title="null"></a> objects using schemes other than :file:<code>http:</code>, :file:<code>ftp:</code>, or :file:<code>file:</code>,<a href="#l1274" title="null"></a> you probably want to use :class:<code>FancyURLopener</code>.<a href="#l1275" title="null"></a> <a href="#l1276" title="null"></a> By default, the :class:<code>URLopener</code> class sends a :mailheader:<code>User-Agent</code> header<a href="#l1277" title="null"></a> of <code>urllib/VVV</code>, where <em>VVV</em> is the :mod:<code>urllib</code> version number.<a href="#l1278" title="null"></a> Applications can define their own :mailheader:<code>User-Agent</code> header by subclassing<a href="#l1279" title="null"></a> :class:<code>URLopener</code> or :class:<code>FancyURLopener</code> and setting the class attribute<a href="#l1280" title="null"></a> :attr:<code>version</code> to an appropriate string value in the subclass definition.<a href="#l1281" title="null"></a> <a href="#l1282" title="null"></a> The optional <em>proxies</em> parameter should be a dictionary mapping scheme names to<a href="#l1283" title="null"></a> proxy URLs, where an empty dictionary turns proxies off completely. Its default<a href="#l1284" title="null"></a> value is <code>None</code>, in which case environmental proxy settings will be used if<a href="#l1285" title="null"></a> present, as discussed in the definition of :func:<code>urlopen</code>, above.<a href="#l1286" title="null"></a> <a href="#l1287" title="null"></a> Additional keyword parameters, collected in <em>x509</em>, may be used for<a href="#l1288" title="null"></a> authentication of the client when using the :file:<code>https:</code> scheme. The keywords<a href="#l1289" title="null"></a> <em>key_file</em> and <em>cert_file</em> are supported to provide an SSL key and certificate;<a href="#l1290" title="null"></a> both are needed to support client authentication.<a href="#l1291" title="null"></a> <a href="#l1292" title="null"></a> :class:<code>URLopener</code> objects will raise an :exc:<code>OSError</code> exception if the server<a href="#l1293" title="null"></a> returns an error code.<a href="#l1294" title="null"></a> <a href="#l1295" title="null"></a> .. method:: open(fullurl, data=None)<a href="#l1296" title="null"></a> <a href="#l1297" title="null"></a> Open <em>fullurl</em> using the appropriate protocol. This method sets up cache and<a href="#l1298" title="null"></a> proxy information, then calls the appropriate open method with its input<a href="#l1299" title="null"></a> arguments. If the scheme is not recognized, :meth:<code>open_unknown</code> is called.<a href="#l1300" title="null"></a> The <em>data</em> argument has the same meaning as the <em>data</em> argument of<a href="#l1301" title="null"></a> :func:<code>urlopen</code>.<a href="#l1302" title="null"></a> <a href="#l1303" title="null"></a> <a href="#l1304" title="null"></a> .. method:: open_unknown(fullurl, data=None)<a href="#l1305" title="null"></a> <a href="#l1306" title="null"></a> Overridable interface to open unknown URL types.<a href="#l1307" title="null"></a> <a href="#l1308" title="null"></a> <a href="#l1309" title="null"></a> .. method:: retrieve(url, filename=None, reporthook=None, data=None)<a href="#l1310" title="null"></a> <a href="#l1311" title="null"></a> Retrieves the contents of <em>url</em> and places it in <em>filename</em>. The return value<a href="#l1312" title="null"></a> is a tuple consisting of a local filename and either a<a href="#l1313" title="null"></a> :class:<code>email.message.Message</code> object containing the response headers (for remote<a href="#l1314" title="null"></a> URLs) or <code>None</code> (for local URLs). The caller must then open and read the<a href="#l1315" title="null"></a> contents of <em>filename</em>. If <em>filename</em> is not given and the URL refers to a<a href="#l1316" title="null"></a> local file, the input filename is returned. If the URL is non-local and<a href="#l1317" title="null"></a> <em>filename</em> is not given, the filename is the output of :func:<code>tempfile.mktemp</code><a href="#l1318" title="null"></a> with a suffix that matches the suffix of the last path component of the input<a href="#l1319" title="null"></a> URL. If <em>reporthook</em> is given, it must be a function accepting three numeric<a href="#l1320" title="null"></a> parameters: A chunk number, the maximum size chunks are read in and the total size of the download<a href="#l1321" title="null"></a> (-1 if unknown). It will be called once at the start and after each chunk of data is read from the<a href="#l1322" title="null"></a> network. <em>reporthook</em> is ignored for local URLs.<a href="#l1323" title="null"></a> <a href="#l1324" title="null"></a> If the <em>url</em> uses the :file:<code>http:</code> scheme identifier, the optional <em>data</em><a href="#l1325" title="null"></a> argument may be given to specify a <code>POST</code> request (normally the request type<a href="#l1326" title="null"></a> is <code>GET</code>). The <em>data</em> argument must in standard<a href="#l1327" title="null"></a> :mimetype:<code>application/x-www-form-urlencoded</code> format; see the<a href="#l1328" title="null"></a> :func:<code>urllib.parse.urlencode</code> function.<a href="#l1329" title="null"></a> <a href="#l1330" title="null"></a> <a href="#l1331" title="null"></a> .. attribute:: version<a href="#l1332" title="null"></a> <a href="#l1333" title="null"></a> Variable that specifies the user agent of the opener object. To get<a href="#l1334" title="null"></a> :mod:<code>urllib</code> to tell servers that it is a particular user agent, set this in a<a href="#l1335" title="null"></a> subclass as a class variable or in the constructor before calling the base<a href="#l1336" title="null"></a> constructor.<a href="#l1337" title="null"></a> <a href="#l1338" title="null"></a> <a href="#l1339" title="null"></a> .. class:: FancyURLopener(...)<a href="#l1340" title="null"></a> <a href="#l1341" title="null"></a> .. deprecated:: 3.3<a href="#l1342" title="null"></a> <a href="#l1343" title="null"></a> :class:<code>FancyURLopener</code> subclasses :class:<code>URLopener</code> providing default handling<a href="#l1344" title="null"></a> for the following HTTP response codes: 301, 302, 303, 307 and 401. For the 30x<a href="#l1345" title="null"></a> response codes listed above, the :mailheader:<code>Location</code> header is used to fetch<a href="#l1346" title="null"></a> the actual URL. For 401 response codes (authentication required), basic HTTP<a href="#l1347" title="null"></a> authentication is performed. For the 30x response codes, recursion is bounded<a href="#l1348" title="null"></a> by the value of the <em>maxtries</em> attribute, which defaults to 10.<a href="#l1349" title="null"></a> <a href="#l1350" title="null"></a> For all other response codes, the method :meth:<code>http_error_default</code> is called<a href="#l1351" title="null"></a> which you can override in subclasses to handle the error appropriately.<a href="#l1352" title="null"></a> <a href="#l1353" title="null"></a> .. note::<a href="#l1354" title="null"></a> <a href="#l1355" title="null"></a> According to the letter of :rfc:<code>2616</code>, 301 and 302 responses to POST requests<a href="#l1356" title="null"></a> must not be automatically redirected without confirmation by the user. In<a href="#l1357" title="null"></a> reality, browsers do allow automatic redirection of these responses, changing<a href="#l1358" title="null"></a> the POST to a GET, and :mod:<code>urllib</code> reproduces this behaviour.<a href="#l1359" title="null"></a> <a href="#l1360" title="null"></a> The parameters to the constructor are the same as those for :class:<code>URLopener</code>.<a href="#l1361" title="null"></a> <a href="#l1362" title="null"></a> .. note::<a href="#l1363" title="null"></a> <a href="#l1364" title="null"></a> When performing basic authentication, a :class:<code>FancyURLopener</code> instance calls<a href="#l1365" title="null"></a> its :meth:<code>prompt_user_passwd</code> method. The default implementation asks the<a href="#l1366" title="null"></a> users for the required information on the controlling terminal. A subclass may<a href="#l1367" title="null"></a> override this method to support more appropriate behavior if needed.<a href="#l1368" title="null"></a> <a href="#l1369" title="null"></a> The :class:<code>FancyURLopener</code> class offers one additional method that should be<a href="#l1370" title="null"></a> overloaded to provide the appropriate behavior:<a href="#l1371" title="null"></a> <a href="#l1372" title="null"></a> .. method:: prompt_user_passwd(host, realm)<a href="#l1373" title="null"></a> <a href="#l1374" title="null"></a> Return information needed to authenticate the user at the given host in the<a href="#l1375" title="null"></a> specified security realm. The return value should be a tuple, <code>(user,[](#l1376) password)</code>, which can be used for basic authentication.<a href="#l1377" title="null"></a> <a href="#l1378" title="null"></a> The implementation prompts for this information on the terminal; an application<a href="#l1379" title="null"></a> should override this method to use an appropriate interaction model in the local<a href="#l1380" title="null"></a> environment.<a href="#l1381" title="null"></a> <a href="#l1382" title="null"></a> <a href="#l1383" title="null"></a> :mod:<code>urllib.request</code> Restrictions<a href="#l1384" title="null"></a> ----------------------------------<a href="#l1385" title="null"></a> <a href="#l1386" title="null"></a> .. index::<a href="#l1387" title="null"></a> pair: HTTP; protocol<a href="#l1388" title="null"></a> pair: FTP; protocol<a href="#l1389" title="null"></a> <a href="#l1390" title="null"></a></p> </blockquote> </blockquote> </blockquote> <ul> <li>Currently, only the following protocols are supported: HTTP (versions 0.9 and<a href="#l1391" title="null"></a> 1.0), FTP, local files, and data URLs.<a href="#l1392" title="null"></a> <a href="#l1393" title="null"></a> .. versionchanged:: 3.4 Added support for data URLs.<a href="#l1394" title="null"></a> <a href="#l1395" title="null"></a></li> <li>The caching feature of :func:<code>urlretrieve</code> has been disabled until someone<a href="#l1396" title="null"></a> finds the time to hack proper processing of Expiration time headers.<a href="#l1397" title="null"></a> <a href="#l1398" title="null"></a></li> <li>There should be a function to query whether a particular URL is in the cache.<a href="#l1399" title="null"></a> <a href="#l1400" title="null"></a></li> <li>For backward compatibility, if a URL appears to point to a local file but the<a href="#l1401" title="null"></a> file can't be opened, the URL is re-interpreted using the FTP protocol. This<a href="#l1402" title="null"></a> can sometimes cause confusing error messages.<a href="#l1403" title="null"></a> <a href="#l1404" title="null"></a></li> <li>The :func:<code>urlopen</code> and :func:<code>urlretrieve</code> functions can cause arbitrarily<a href="#l1405" title="null"></a> long delays while waiting for a network connection to be set up. This means<a href="#l1406" title="null"></a> that it is difficult to build an interactive Web client using these functions<a href="#l1407" title="null"></a> without using threads.<a href="#l1408" title="null"></a> <a href="#l1409" title="null"></a> .. index::<a href="#l1410" title="null"></a> single: HTML<a href="#l1411" title="null"></a> pair: HTTP; protocol<a href="#l1412" title="null"></a> <a href="#l1413" title="null"></a></li> <li>The data returned by :func:<code>urlopen</code> or :func:<code>urlretrieve</code> is the raw data<a href="#l1414" title="null"></a> returned by the server. This may be binary data (such as an image), plain text<a href="#l1415" title="null"></a> or (for example) HTML. The HTTP protocol provides type information in the reply<a href="#l1416" title="null"></a> header, which can be inspected by looking at the :mailheader:<code>Content-Type</code><a href="#l1417" title="null"></a> header. If the returned data is HTML, you can use the module<a href="#l1418" title="null"></a> :mod:<code>html.parser</code> to parse it.<a href="#l1419" title="null"></a> <a href="#l1420" title="null"></a> .. index:: single: FTP<a href="#l1421" title="null"></a> <a href="#l1422" title="null"></a></li> <li>The code handling the FTP protocol cannot differentiate between a file and a<a href="#l1423" title="null"></a> directory. This can lead to unexpected behavior when attempting to read a URL<a href="#l1424" title="null"></a> that points to a file that is not accessible. If the URL ends in a <code>/</code>, it is<a href="#l1425" title="null"></a> assumed to refer to a directory and will be handled accordingly. But if an<a href="#l1426" title="null"></a> attempt to read a file leads to a 550 error (meaning the URL cannot be found or<a href="#l1427" title="null"></a> is not accessible, often for permission reasons), then the path is treated as a<a href="#l1428" title="null"></a> directory in order to handle the case when a directory is specified by a URL but<a href="#l1429" title="null"></a> the trailing <code>/</code> has been left off. This can cause misleading results when<a href="#l1430" title="null"></a> you try to fetch a file whose read permissions make it inaccessible; the FTP<a href="#l1431" title="null"></a> code will try to read it, fail with a 550 error, and then perform a directory<a href="#l1432" title="null"></a> listing for the unreadable file. If fine-grained control is needed, consider<a href="#l1433" title="null"></a> using the :mod:<code>ftplib</code> module, subclassing :class:<code>FancyURLopener</code>, or changing<a href="#l1434" title="null"></a> <em>_urlopener</em> to meet your needs.<a href="#l1435" title="null"></a> <a href="#l1436" title="null"></a> <a href="#l1437" title="null"></a> <a href="#l1438" title="null"></a> :mod:<code>urllib.response</code> --- Response classes used by urllib<a href="#l1439" title="null"></a> ==========================================================<a href="#l1440" title="null"></a> <a href="#l1441" title="null"></a> .. module:: urllib.response<a href="#l1442" title="null"></a> :synopsis: Response classes used by urllib.<a href="#l1443" title="null"></a> <a href="#l1444" title="null"></a> The :mod:<code>urllib.response</code> module defines functions and classes which define a<a href="#l1445" title="null"></a> minimal file like interface, including <code>read()</code> and <code>readline()</code>. The<a href="#l1446" title="null"></a> typical response object is an addinfourl instance, which defines an <code>info()</code><a href="#l1447" title="null"></a> method and that returns headers and a <code>geturl()</code> method that returns the url.<a href="#l1448" title="null"></a> Functions defined by this module are used internally by the<a href="#l1449" title="null"></a> :mod:<code>urllib.request</code> module.<a href="#l1450" title="null"></a> <a href="#l1451" title="null"></a></li> </ul>