urllib.request — Extensible library for opening URLs

Source code:Lib/urllib/request.py


Theurllib.request module defines functions and classes which help inopening URLs (mostly HTTP) in a complex world — basic and digestauthentication, redirections, cookies and more.

See also

TheRequests packageis recommended for a higher-level HTTP client interface.

Warning

On macOS it is unsafe to use this module in programs usingos.fork() because thegetproxies() implementation formacOS uses a higher-level system API. Set the environment variableno_proxy to* to avoid this problem(e.g.os.environ["no_proxy"]="*").

Availability: not WASI.

This module does not work or is not available on WebAssembly. SeeWebAssembly platforms for more information.

Theurllib.request module defines the following functions:

urllib.request.urlopen(url,data=None,[timeout,]*,context=None)

Openurl, which can be either a string containing a valid, properlyencoded URL, or aRequest object.

data must be an object specifying additional data to be sent to theserver, orNone if no such data is needed. SeeRequestfor details.

urllib.request module uses HTTP/1.1 and includesConnection:close headerin its HTTP requests.

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

Ifcontext is specified, it must be assl.SSLContext instancedescribing the various SSL options. SeeHTTPSConnectionfor more details.

This function always returns an object which can work as acontext manager and has the propertiesurl,headers, andstatus.Seeurllib.response.addinfourl for more detail on these properties.

For HTTP and HTTPS URLs, this function returns ahttp.client.HTTPResponse object slightly modified. In additionto the three new methods above, the msg attribute contains thesame information as thereasonattribute — the reason phrase returned by server — instead ofthe response headers as it is specified in the documentation forHTTPResponse.

For FTP, file, and data URLs and requests explicitly handled by legacyURLopener andFancyURLopener classes, this functionreturns aurllib.response.addinfourl object.

RaisesURLError on protocol errors.

Note thatNone may be returned if no handler handles the request (thoughthe default installed globalOpenerDirector usesUnknownHandler to ensure this never happens).

In addition, if proxy settings are detected (for example, when a*_proxyenvironment variable likehttp_proxy is set),ProxyHandler is default installed and makes sure the requests arehandled through the proxy.

The legacyurllib.urlopen function from Python 2.6 and earlier has beendiscontinued;urllib.request.urlopen() corresponds to the oldurllib2.urlopen. Proxy handling, which was done by passing a dictionaryparameter tourllib.urlopen, can be obtained by usingProxyHandler objects.

The default opener raises anauditing eventurllib.Request with argumentsfullurl,data,headers,method taken from the request object.

Changed in version 3.2:cafile andcapath were added.

HTTPS virtual hosts are now supported if possible (that is, ifssl.HAS_SNI is true).

data can be an iterable object.

Changed in version 3.3:cadefault was added.

Changed in version 3.4.3:context was added.

Changed in version 3.10:HTTPS connection now send an ALPN extension with protocol indicatorhttp/1.1 when nocontext is given. Customcontext should setALPN protocols withset_alpn_protocols().

Changed in version 3.13:Removecafile,capath andcadefault parameters: use thecontextparameter instead.

urllib.request.install_opener(opener)

Install anOpenerDirector instance as the default global opener.Installing an opener is only necessary if you want urlopen to use thatopener; otherwise, simply callOpenerDirector.open() instead ofurlopen(). The code does not check for a realOpenerDirector, and any class with the appropriate interface willwork.

urllib.request.build_opener([handler,...])

Return anOpenerDirector instance, which chains the handlers in theorder given.handlers can be either instances ofBaseHandler, orsubclasses ofBaseHandler (in which case it must be possible to callthe constructor without any parameters). Instances of the following classeswill be in front of thehandlers, unless thehandlers contain them,instances of them or subclasses of them:ProxyHandler (if proxysettings are detected),UnknownHandler,HTTPHandler,HTTPDefaultErrorHandler,HTTPRedirectHandler,FTPHandler,FileHandler,HTTPErrorProcessor.

If the Python installation has SSL support (i.e., if thessl modulecan be imported),HTTPSHandler will also be added.

ABaseHandler subclass may also change itshandler_orderattribute to modify its position in the handlers list.

urllib.request.pathname2url(path)

Convert the given local path to afile: URL. This function usesquote() function to encode the path. For historicalreasons, the return value omits thefile: scheme prefix. This exampleshows the function being used on Windows:

>>>fromurllib.requestimportpathname2url>>>path='C:\\Program Files'>>>'file:'+pathname2url(path)'file:///C:/Program%20Files'
urllib.request.url2pathname(url)

Convert the givenfile: URL to a local path. This function usesunquote() to decode the URL. For historical reasons,the given valuemust omit thefile: scheme prefix. This example showsthe function being used on Windows:

>>>fromurllib.requestimporturl2pathname>>>url='file:///C:/Program%20Files'>>>url2pathname(url.removeprefix('file:'))'C:\\Program Files'
urllib.request.getproxies()

This helper function returns a dictionary of scheme to proxy server URLmappings. It scans the environment for variables named<scheme>_proxy,in a case insensitive approach, for all operating systems first, and when itcannot find it, looks for proxy information from SystemConfiguration for macOS and Windows Systems Registry for Windows.If both lowercase and uppercase environment variables exist (and disagree),lowercase is preferred.

Note

If the environment variableREQUEST_METHOD is set, which usuallyindicates your script is running in a CGI environment, the environmentvariableHTTP_PROXY (uppercase_PROXY) will be ignored. This isbecause that variable can be injected by a client using the “Proxy:” HTTPheader. If you need to use an HTTP proxy in a CGI environment, either useProxyHandler explicitly, or make sure the variable name is inlowercase (or at least the_proxy suffix).

The following classes are provided:

classurllib.request.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, properly encoded URL.

data must be an object specifying additional data to send to theserver, orNone if no such data is needed. Currently HTTPrequests are the only ones that usedata. The supported objecttypes include bytes, file-like objects, and iterables of bytes-like objects.If noContent-Length norTransfer-Encoding header fieldhas been provided,HTTPHandler will set these headers accordingto the type ofdata.Content-Length will be used to sendbytes objects, whileTransfer-Encoding:chunked as specified inRFC 7230, Section 3.3.1 will be used to send files and other iterables.

For an HTTP POST request method,data should be a buffer in thestandardapplication/x-www-form-urlencoded format. Theurllib.parse.urlencode() function takes a mapping or sequenceof 2-tuples and returns an ASCII string in this format. It shouldbe encoded to bytes before being used as thedata parameter.

headers should be a dictionary, and will be treated as ifadd_header() was called with each key and value as arguments.This is often used to “spoof” theUser-Agent header value, which isused by a browser to identify itself – some HTTP servers onlyallow 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", whileurllib’s default user agent string is"Python-urllib/2.6" (on Python 2.6).All header keys are sent in camel case.

An appropriateContent-Type header should be included if thedataargument is present. If this header has not been provided anddatais notNone,Content-Type:application/x-www-form-urlencoded willbe added as a default.

The next two arguments are only of interest for correct handlingof third-party HTTP cookies:

origin_req_host should be the request-host of the origintransaction, as defined byRFC 2965. It defaults tohttp.cookiejar.request_host(self). This is the host name or IPaddress 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 pagecontaining the image.

unverifiable should indicate whether the request is unverifiable,as defined byRFC 2965. It defaults toFalse. An unverifiablerequest is one whose URL the user did not have the option toapprove. For example, if the request is for an image in an HTMLdocument, and the user had no option to approve the automaticfetching of the image, this should be true.

method should be a string that indicates the HTTP request method thatwill be used (e.g.'HEAD'). If provided, its value is stored in themethod attribute and is used byget_method().The default is'GET' ifdata isNone or'POST' otherwise.Subclasses may indicate a different default method by setting themethod attribute in the class itself.

Note

The request will not work as expected if the data object is unableto deliver its content more than once (e.g. a file or an iterablethat can produce the content only once) and the request is retriedfor HTTP redirects or authentication. Thedata is sent to theHTTP server right away after the headers. There is no support fora 100-continue expectation in the library.

Changed in version 3.3:Request.method argument is added to the Request class.

Changed in version 3.4:DefaultRequest.method may be indicated at the class level.

Changed in version 3.6:Do not raise an error if theContent-Length has not beenprovided anddata is neitherNone nor a bytes object.Fall back to use chunked transfer encoding instead.

classurllib.request.OpenerDirector

TheOpenerDirector class opens URLs viaBaseHandlers chainedtogether. It manages the chaining of handlers, and recovery from errors.

classurllib.request.BaseHandler

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

classurllib.request.HTTPDefaultErrorHandler

A class which defines a default handler for HTTP error responses; all responsesare turned intoHTTPError exceptions.

classurllib.request.HTTPRedirectHandler

A class to handle redirections.

classurllib.request.HTTPCookieProcessor(cookiejar=None)

A class to handle HTTP Cookies.

classurllib.request.ProxyHandler(proxies=None)

Cause requests to go through a proxy. Ifproxies is given, it must be adictionary mapping protocol names to URLs of proxies. The default is to readthe list of proxies from the environment variables<protocol>_proxy. If no proxy environment variables are set, thenin a Windows environment proxy settings are obtained from the registry’sInternet Settings section, and in a macOS environment proxy informationis retrieved from the System Configuration Framework.

To disable autodetected proxy pass an empty dictionary.

Theno_proxy environment variable can be used to specify hostswhich shouldn’t be reached via proxy; if set, it should be a comma-separatedlist of hostname suffixes, optionally with:port appended, for examplecern.ch,ncsa.uiuc.edu,some.host:8080.

Note

HTTP_PROXY will be ignored if a variableREQUEST_METHOD is set;see the documentation ongetproxies().

classurllib.request.HTTPPasswordMgr

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

classurllib.request.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 realmfits.

classurllib.request.HTTPPasswordMgrWithPriorAuth

A variant ofHTTPPasswordMgrWithDefaultRealm that also has adatabase ofuri->is_authenticated mappings. Can be used by aBasicAuth handler to determine when to send authentication credentialsimmediately instead of waiting for a401 response first.

Added in version 3.5.

classurllib.request.AbstractBasicAuthHandler(password_mgr=None)

This is a mixin class that helps with HTTP authentication, both to the remotehost and to a proxy.password_mgr, if given, should be something that iscompatible withHTTPPasswordMgr; refer to sectionHTTPPasswordMgr Objects for information on the interface that must besupported. Ifpasswd_mgr also providesis_authenticated andupdate_authenticated methods (seeHTTPPasswordMgrWithPriorAuth Objects), then the handler will use theis_authenticated result for a given URI to determine whether or not tosend authentication credentials with the request. Ifis_authenticatedreturnsTrue for the URI, credentials are sent. Ifis_authenticatedisFalse, credentials are not sent, and then if a401 response isreceived the request is re-sent with the authentication credentials. Ifauthentication succeeds,update_authenticated is called to setis_authenticatedTrue for the URI, so that subsequent requests tothe URI or any of its super-URIs will automatically include theauthentication credentials.

Added in version 3.5:Addedis_authenticated support.

classurllib.request.HTTPBasicAuthHandler(password_mgr=None)

Handle authentication with the remote host.password_mgr, if given, shouldbe something that is compatible withHTTPPasswordMgr; refer tosectionHTTPPasswordMgr Objects for information on the interface that mustbe supported. HTTPBasicAuthHandler will raise aValueError whenpresented with a wrong Authentication scheme.

classurllib.request.ProxyBasicAuthHandler(password_mgr=None)

Handle authentication with the proxy.password_mgr, if given, should besomething that is compatible withHTTPPasswordMgr; refer to sectionHTTPPasswordMgr Objects for information on the interface that must besupported.

classurllib.request.AbstractDigestAuthHandler(password_mgr=None)

This is a mixin class that helps with HTTP authentication, both to the remotehost and to a proxy.password_mgr, if given, should be something that iscompatible withHTTPPasswordMgr; refer to sectionHTTPPasswordMgr Objects for information on the interface that must besupported.

classurllib.request.HTTPDigestAuthHandler(password_mgr=None)

Handle authentication with the remote host.password_mgr, if given, shouldbe something that is compatible withHTTPPasswordMgr; refer tosectionHTTPPasswordMgr Objects for information on the interface that mustbe supported. When both Digest Authentication Handler and BasicAuthentication Handler are both added, Digest Authentication is always triedfirst. If the Digest Authentication returns a 40x response again, it is sentto Basic Authentication handler to Handle. This Handler method will raise aValueError when presented with an authentication scheme other thanDigest or Basic.

Changed in version 3.3:RaiseValueError on unsupported Authentication Scheme.

classurllib.request.ProxyDigestAuthHandler(password_mgr=None)

Handle authentication with the proxy.password_mgr, if given, should besomething that is compatible withHTTPPasswordMgr; refer to sectionHTTPPasswordMgr Objects for information on the interface that must besupported.

classurllib.request.HTTPHandler

A class to handle opening of HTTP URLs.

classurllib.request.HTTPSHandler(debuglevel=0,context=None,check_hostname=None)

A class to handle opening of HTTPS URLs.context andcheck_hostnamehave the same meaning as inhttp.client.HTTPSConnection.

Changed in version 3.2:context andcheck_hostname were added.

classurllib.request.FileHandler

Open local files.

classurllib.request.DataHandler

Open data URLs.

Added in version 3.4.

classurllib.request.FTPHandler

Open FTP URLs.

classurllib.request.CacheFTPHandler

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

classurllib.request.UnknownHandler

A catch-all class to handle unknown URLs.

classurllib.request.HTTPErrorProcessor

Process HTTP error responses.

Request Objects

The following methods describeRequest’s public interface,and so all may be overridden in subclasses. It also defines severalpublic attributes that can be used by clients to inspect the parsedrequest.

Request.full_url

The original URL passed to the constructor.

Changed in version 3.4.

Request.full_url is a property with setter, getter and a deleter. Gettingfull_url returns the original request URL with thefragment, if it was present.

Request.type

The URI scheme.

Request.host

The URI authority, typically a host, but may also contain a portseparated by a colon.

Request.origin_req_host

The original host for the request, without port.

Request.selector

The URI path. If theRequest uses a proxy, then selectorwill be the full URL that is passed to the proxy.

Request.data

The entity body for the request, orNone if not specified.

Changed in version 3.4:Changing value ofRequest.data now deletes “Content-Length”header if it was previously set or calculated.

Request.unverifiable

boolean, indicates whether the request is unverifiable as definedbyRFC 2965.

Request.method

The HTTP request method to use. By default its value isNone,which means thatget_method() will do its normal computationof the method to be used. Its value can be set (thus overriding the defaultcomputation inget_method()) either by providing a defaultvalue by setting it at the class level in aRequest subclass, or bypassing a value in to theRequest constructor via themethodargument.

Added in version 3.3.

Changed in version 3.4:A default value can now be set in subclasses; previously it could onlybe set via the constructor argument.

Request.get_method()

Return a string indicating the HTTP request method. IfRequest.method is notNone, return its value, otherwise return'GET' ifRequest.data isNone, or'POST' if it’s not.This is only meaningful for HTTP requests.

Changed in version 3.3:get_method now looks at the value ofRequest.method.

Request.add_header(key,val)

Add another header to the request. Headers are currently ignored by allhandlers except HTTP handlers, where they are added to the list of headers sentto the server. Note that there cannot be more than one header with the samename, and later calls will overwrite previous calls in case thekey collides.Currently, this is no loss of HTTP functionality, since all headers which havemeaning when used more than once have a (header-specific) way of gaining thesame functionality using only one header. Note that headers added usingthis method are also added to redirected requests.

Request.add_unredirected_header(key,header)

Add a header that will not be added to a redirected request.

Request.has_header(header)

Return whether the instance has the named header (checks both regular andunredirected).

Request.remove_header(header)

Remove named header from the request instance (both from regular andunredirected headers).

Added in version 3.4.

Request.get_full_url()

Return the URL given in the constructor.

Changed in version 3.4.

ReturnsRequest.full_url

Request.set_proxy(host,type)

Prepare the request by connecting to a proxy server. Thehost andtype willreplace those of the instance, and the instance’s selector will be the originalURL given in the constructor.

Request.get_header(header_name,default=None)

Return the value of the given header. If the header is not present, returnthe default value.

Request.header_items()

Return a list of tuples (header_name, header_value) of the Request headers.

Changed in version 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 deprecatedsince 3.3 have been removed.

OpenerDirector Objects

OpenerDirector instances have the following methods:

OpenerDirector.add_handler(handler)

handler should be an instance ofBaseHandler. The following methodsare searched, and added to the possible chains (note that HTTP errors are aspecial case). Note that, in the following,protocol should be replacedwith the actual protocol to handle, for examplehttp_response() wouldbe the HTTP protocol response handler. Alsotype should be replaced withthe actual HTTP code, for examplehttp_error_404() would handle HTTP404 errors.

  • <protocol>_open() — signal that the handler knows how to openprotocolURLs.

    SeeBaseHandler.<protocol>_open() for more information.

  • http_error_<type>() — signal that the handler knows how to handle HTTPerrors with HTTP error codetype.

    SeeBaseHandler.http_error_<nnn>() for more information.

  • <protocol>_error() — signal that the handler knows how to handle errorsfrom (non-http)protocol.

  • <protocol>_request() — signal that the handler knows how to pre-processprotocol requests.

    SeeBaseHandler.<protocol>_request() for more information.

  • <protocol>_response() — signal that the handler knows how topost-processprotocol responses.

    SeeBaseHandler.<protocol>_response() for more information.

OpenerDirector.open(url,data=None[,timeout])

Open the givenurl (which can be a request object or a string), optionallypassing the givendata. Arguments, return values and exceptions raised arethe same as those ofurlopen() (which simply calls theopen()method on the currently installed globalOpenerDirector). Theoptionaltimeout parameter specifies a timeout in seconds for blockingoperations like the connection attempt (if not specified, the global defaulttimeout setting will be used). The timeout feature actually works only forHTTP, HTTPS and FTP connections.

OpenerDirector.error(proto,*args)

Handle an error of the given protocol. This will call the registered errorhandlers for the given protocol with the given arguments (which are protocolspecific). The HTTP protocol is a special case which uses the HTTP responsecode to determine the specific error handler; refer to thehttp_error_<type>()methods of the handler classes.

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

OpenerDirector objects open URLs in three stages:

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

  1. Every handler with a method named like<protocol>_request() has thatmethod called to pre-process the request.

  2. Handlers with a method named like<protocol>_open() are called to handlethe request. This stage ends when a handler either returns a non-Nonevalue (ie. a response), or raises an exception (usuallyURLError). Exceptions are allowed to propagate.

    In fact, the above algorithm is first tried for methods nameddefault_open(). If all such methods returnNone, the algorithmis repeated for methods named like<protocol>_open(). If all such methodsreturnNone, the algorithm is repeated for methods namedunknown_open().

    Note that the implementation of these methods may involve calls of the parentOpenerDirector instance’sopen() anderror() methods.

  3. Every handler with a method named like<protocol>_response() has thatmethod called to post-process the response.

BaseHandler Objects

BaseHandler objects provide a couple of methods that are directlyuseful, and others that are meant to be used by derived classes. These areintended for direct use:

BaseHandler.add_parent(director)

Add a director as parent.

BaseHandler.close()

Remove any parents.

The following attribute and methods should only be used by classes derived fromBaseHandler.

Note

The convention has been adopted that subclasses defining<protocol>_request() or<protocol>_response() methods are named*Processor; all others are named*Handler.

BaseHandler.parent

A validOpenerDirector, which can be used to open using a differentprotocol, or handle errors.

BaseHandler.default_open(req)

This method isnot defined inBaseHandler, but subclasses shoulddefine it if they want to catch all URLs.

This method, if implemented, will be called by the parentOpenerDirector. It should return a file-like object as described inthe return value of theopen() method ofOpenerDirector, orNone.It should raiseURLError, unless a truly exceptionalthing happens (for example,MemoryError should not be mapped toURLError).

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

BaseHandler.<protocol>_open(req)

This method isnot defined inBaseHandler, but subclasses shoulddefine it if they want to handle URLs with the given protocol.

This method, if defined, will be called by the parentOpenerDirector.Return values should be the same as fordefault_open().

BaseHandler.unknown_open(req)

This method isnot defined inBaseHandler, but subclasses shoulddefine it if they want to catch all URLs with no specific registered handler toopen it.

This method, if implemented, will be called by theparentOpenerDirector. Return values should be the same as fordefault_open().

BaseHandler.http_error_default(req,fp,code,msg,hdrs)

This method isnot defined inBaseHandler, but subclasses shouldoverride it if they intend to provide a catch-all for otherwise unhandled HTTPerrors. It will be called automatically by theOpenerDirector gettingthe error, and should not normally be called in other circumstances.

req will be aRequest object,fp will be a file-like object withthe HTTP error body,code will be the three-digit code of the error,msgwill be the user-visible explanation of the code andhdrs will be a mappingobject with the headers of the error.

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

BaseHandler.http_error_<nnn>(req,fp,code,msg,hdrs)

nnn should be a three-digit HTTP error code. This method is also not definedinBaseHandler, but will be called, if it exists, on an instance of asubclass, when an HTTP error with codennn occurs.

Subclasses should override this method to handle specific HTTP errors.

Arguments, return values and exceptions raised should be the same as forhttp_error_default().

BaseHandler.<protocol>_request(req)

This method isnot defined inBaseHandler, but subclasses shoulddefine it if they want to pre-process requests of the given protocol.

This method, if defined, will be called by the parentOpenerDirector.req will be aRequest object. The return value should be aRequest object.

BaseHandler.<protocol>_response(req,response)

This method isnot defined inBaseHandler, but subclasses shoulddefine it if they want to post-process responses of the given protocol.

This method, if defined, will be called by the parentOpenerDirector.req will be aRequest object.response will be an objectimplementing the same interface as the return value ofurlopen(). Thereturn value should implement the same interface as the return value ofurlopen().

HTTPRedirectHandler Objects

Note

Some HTTP redirections require action from this module’s client code. If thisis the case,HTTPError is raised. SeeRFC 2616 fordetails of the precise meanings of the various redirection codes.

AnHTTPError exception raised as a security consideration if theHTTPRedirectHandler is presented with a redirected URL which is not an HTTP,HTTPS or FTP URL.

HTTPRedirectHandler.redirect_request(req,fp,code,msg,hdrs,newurl)

Return aRequest orNone in response to a redirect. This is calledby the default implementations of thehttp_error_30*() methods when aredirection is received from the server. If a redirection should take place,return a newRequest to allowhttp_error_30*() to perform theredirect tonewurl. Otherwise, raiseHTTPError ifno other handler should try to handle this URL, or returnNone if youcan’t but another handler might.

Note

The default implementation of this method does not strictly followRFC 2616,which says that 301 and 302 responses toPOST requests must not beautomatically redirected without confirmation by the user. In reality, browsersdo allow automatic redirection of these responses, changing the POST to aGET, and the default implementation reproduces this behavior.

HTTPRedirectHandler.http_error_301(req,fp,code,msg,hdrs)

Redirect to theLocation: orURI: URL. This method is called by theparentOpenerDirector when getting an HTTP ‘moved permanently’ response.

HTTPRedirectHandler.http_error_302(req,fp,code,msg,hdrs)

The same ashttp_error_301(), but called for the ‘found’ response.

HTTPRedirectHandler.http_error_303(req,fp,code,msg,hdrs)

The same ashttp_error_301(), but called for the ‘see other’ response.

HTTPRedirectHandler.http_error_307(req,fp,code,msg,hdrs)

The same ashttp_error_301(), but called for the ‘temporary redirect’response. It does not allow changing the request method fromPOSTtoGET.

HTTPRedirectHandler.http_error_308(req,fp,code,msg,hdrs)

The same ashttp_error_301(), but called for the ‘permanent redirect’response. It does not allow changing the request method fromPOSTtoGET.

Added in version 3.11.

HTTPCookieProcessor Objects

HTTPCookieProcessor instances have one attribute:

HTTPCookieProcessor.cookiejar

Thehttp.cookiejar.CookieJar in which cookies are stored.

ProxyHandler Objects

ProxyHandler.<protocol>_open(request)

TheProxyHandler will have a method<protocol>_open() for everyprotocol which has a proxy in theproxies dictionary given in theconstructor. The method will modify requests to go through the proxy, bycallingrequest.set_proxy(), and call the next handler in the chain toactually execute the protocol.

HTTPPasswordMgr Objects

These methods are available onHTTPPasswordMgr andHTTPPasswordMgrWithDefaultRealm objects.

HTTPPasswordMgr.add_password(realm,uri,user,passwd)

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

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.

ForHTTPPasswordMgrWithDefaultRealm objects, the realmNone will besearched if the givenrealm has no matching user/password.

HTTPPasswordMgrWithPriorAuth Objects

This password manager extendsHTTPPasswordMgrWithDefaultRealm to supporttracking URIs for which authentication credentials should always be sent.

HTTPPasswordMgrWithPriorAuth.add_password(realm,uri,user,passwd,is_authenticated=False)

realm,uri,user,passwd are as forHTTPPasswordMgr.add_password().is_authenticated sets the initialvalue of theis_authenticated flag for the given URI or list of URIs.Ifis_authenticated is specified asTrue,realm is ignored.

HTTPPasswordMgrWithPriorAuth.find_user_password(realm,authuri)

Same as forHTTPPasswordMgrWithDefaultRealm objects

HTTPPasswordMgrWithPriorAuth.update_authenticated(self,uri,is_authenticated=False)

Update theis_authenticated flag for the givenuri or listof URIs.

HTTPPasswordMgrWithPriorAuth.is_authenticated(self,authuri)

Returns the current state of theis_authenticated flag forthe given URI.

AbstractBasicAuthHandler Objects

AbstractBasicAuthHandler.http_error_auth_reqed(authreq,host,req,headers)

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

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

HTTPBasicAuthHandler Objects

HTTPBasicAuthHandler.http_error_401(req,fp,code,msg,hdrs)

Retry the request with authentication information, if available.

ProxyBasicAuthHandler Objects

ProxyBasicAuthHandler.http_error_407(req,fp,code,msg,hdrs)

Retry the request with authentication information, if available.

AbstractDigestAuthHandler Objects

AbstractDigestAuthHandler.http_error_auth_reqed(authreq,host,req,headers)

authreq should be the name of the header where the information about the realmis included in the request,host should be the host to authenticate to,reqshould be the (failed)Request object, andheaders should be theerror headers.

HTTPDigestAuthHandler Objects

HTTPDigestAuthHandler.http_error_401(req,fp,code,msg,hdrs)

Retry the request with authentication information, if available.

ProxyDigestAuthHandler Objects

ProxyDigestAuthHandler.http_error_407(req,fp,code,msg,hdrs)

Retry the request with authentication information, if available.

HTTPHandler Objects

HTTPHandler.http_open(req)

Send an HTTP request, which can be either GET or POST, depending onreq.data.

HTTPSHandler Objects

HTTPSHandler.https_open(req)

Send an HTTPS request, which can be either GET or POST, depending onreq.data.

FileHandler Objects

FileHandler.file_open(req)

Open the file locally, if there is no host name, or the host name is'localhost'.

Changed in version 3.2:This method is applicable only for local hostnames. When a remotehostname is given, aURLError is raised.

DataHandler Objects

DataHandler.data_open(req)

Read a data URL. This kind of URL contains the content encoded in the URLitself. The data URL syntax is specified inRFC 2397. This implementationignores white spaces in base64 encoded data URLs so the URL may be wrappedin whatever source file it comes from. But even though some browsers don’tmind about a missing padding at the end of a base64 encoded data URL, thisimplementation will raise aValueError in that case.

FTPHandler Objects

FTPHandler.ftp_open(req)

Open the FTP file indicated byreq. The login is always done with emptyusername and password.

CacheFTPHandler Objects

CacheFTPHandler objects areFTPHandler objects with thefollowing additional methods:

CacheFTPHandler.setTimeout(t)

Set timeout of connections tot seconds.

CacheFTPHandler.setMaxConns(m)

Set maximum number of cached connections tom.

UnknownHandler Objects

UnknownHandler.unknown_open()

Raise aURLError exception.

HTTPErrorProcessor Objects

HTTPErrorProcessor.http_response(request,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 thehttp_error_<type>() handler methods, viaOpenerDirector.error().Eventually,HTTPDefaultErrorHandler will raise anHTTPError if no other handler handles the error.

HTTPErrorProcessor.https_response(request,response)

Process HTTPS error responses.

The behavior is same ashttp_response().

Examples

In addition to the examples below, more examples are given inHOWTO Fetch Internet Resources Using The urllib Package.

This example gets the python.org main page and displays the first 300 bytes ofit:

>>>importurllib.request>>>withurllib.request.urlopen('http://www.python.org/')asf:...print(f.read(300))...b'<!doctype html>\n<!--[if lt IE 7]>   <html class="no-js ie6 lt-ie7 lt-ie8 lt-ie9">   <![endif]-->\n<!--[if IE 7]>      <html class="no-js ie7 lt-ie8 lt-ie9">          <![endif]-->\n<!--[if IE 8]>      <html class="no-js ie8 lt-ie9">

Note that urlopen returns a bytes object. This is because there is no wayfor urlopen to automatically determine the encoding of the byte streamit receives from the HTTP server. In general, a program will decodethe returned bytes object to string once it determines or guessesthe appropriate encoding.

The following HTML spec document,https://html.spec.whatwg.org/#charset, liststhe various ways in which an HTML or an XML document could have specified itsencoding information.

For additional information, see the W3C document:https://www.w3.org/International/questions/qa-html-encoding-declarations.

As the python.org website usesutf-8 encoding as specified in its meta tag, wewill use the same for decoding the bytes object:

>>>withurllib.request.urlopen('http://www.python.org/')asf:...print(f.read(100).decode('utf-8'))...<!doctype html><!--[if lt IE 7]>   <html class="no-js ie6 lt-ie7 lt-ie8 lt-ie9">   <![endif]--><!-

It is also possible to achieve the same result without using thecontext manager approach:

>>>importurllib.request>>>f=urllib.request.urlopen('http://www.python.org/')>>>try:...print(f.read(100).decode('utf-8'))...finally:...f.close()...<!doctype html><!--[if lt IE 7]>   <html class="no-js ie6 lt-ie7 lt-ie8 lt-ie9">   <![endif]--><!--

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

>>>importurllib.request>>>req=urllib.request.Request(url='https://localhost/cgi-bin/test.cgi',...data=b'This data is passed to stdin of the CGI')>>>withurllib.request.urlopen(req)asf:...print(f.read().decode('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 pythonimportsysdata=sys.stdin.read()print('Content-type: text/plain\n\nGot Data: "%s"'%data)

Here is an example of doing aPUT request usingRequest:

importurllib.requestDATA=b'some data'req=urllib.request.Request(url='http://localhost:8080',data=DATA,method='PUT')withurllib.request.urlopen(req)asf:passprint(f.status)print(f.reason)

Use of Basic HTTP Authentication:

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

build_opener() provides many handlers by default, including aProxyHandler. By default,ProxyHandler uses the environmentvariables named<scheme>_proxy, where<scheme> is the URL schemeinvolved. For example, thehttp_proxy environment variable is read toobtain the HTTP proxy’s URL.

This example replaces the defaultProxyHandler with one that usesprogrammatically supplied proxy URLs, and adds proxy authorization support withProxyBasicAuthHandler.

proxy_handler=urllib.request.ProxyHandler({'http':'http://www.example.com:3128/'})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:withopener.open('http://www.example.com/login.html')asf:print(f.read().decode('utf-8'))

Adding HTTP headers:

Use theheaders argument to theRequest constructor, or:

importurllib.requestreq=urllib.request.Request('http://www.example.com/')req.add_header('Referer','http://www.python.org/')# Customize the default User-Agent header value:req.add_header('User-Agent','urllib-example/0.1 (Contact: . . .)')withurllib.request.urlopen(req)asf:print(f.read().decode('utf-8'))

OpenerDirector automatically adds aUser-Agent header toeveryRequest. To change this:

importurllib.requestopener=urllib.request.build_opener()opener.addheaders=[('User-agent','Mozilla/5.0')]withopener.open('http://www.example.com/')asf:print(f.read().decode('utf-8'))

Also, remember that a few standard headers (Content-Length,Content-Type andHost)are added when theRequest is passed tourlopen() (orOpenerDirector.open()).

Here is an example session that uses theGET method to retrieve a URLcontaining parameters:

>>>importurllib.request>>>importurllib.parse>>>params=urllib.parse.urlencode({'spam':1,'eggs':2,'bacon':0})>>>url="http://www.musi-cal.com/cgi-bin/query?%s"%params>>>withurllib.request.urlopen(url)asf:...print(f.read().decode('utf-8'))...

The following example uses thePOST method instead. Note that params outputfrom urlencode is encoded to bytes before it is sent to urlopen as data:

>>>importurllib.request>>>importurllib.parse>>>data=urllib.parse.urlencode({'spam':1,'eggs':2,'bacon':0})>>>data=data.encode('ascii')>>>withurllib.request.urlopen("http://requestb.in/xrbl82xr",data)asf:...print(f.read().decode('utf-8'))...

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

>>>importurllib.request>>>proxies={'http':'http://proxy.example.com:8080/'}>>>opener=urllib.request.FancyURLopener(proxies)>>>withopener.open("http://www.python.org")asf:...f.read().decode('utf-8')...

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

>>>importurllib.request>>>opener=urllib.request.FancyURLopener({})>>>withopener.open("http://www.python.org/")asf:...f.read().decode('utf-8')...

Legacy interface

The following functions and classes are ported from the Python 2 moduleurllib (as opposed tourllib2). They might become deprecated atsome point in the future.

urllib.request.urlretrieve(url,filename=None,reporthook=None,data=None)

Copy a network object denoted by a URL to a local file. If the URLpoints to a local file, the object will not be copied unless filename is supplied.Return a tuple(filename,headers) wherefilename is thelocal file name under which the object can be found, andheaders is whatevertheinfo() method of the object returned byurlopen() returned (fora remote object). Exceptions are the same as forurlopen().

The second argument, if present, specifies the file location to copy to (ifabsent, the location will be a tempfile with a generated name). The thirdargument, if present, is a callable that will be called once onestablishment of the network connection and once after each block readthereafter. The callable will be passed three arguments; a count of blockstransferred so far, a block size in bytes, and the total size of the file. Thethird argument may be-1 on older FTP servers which do not return a filesize in response to a retrieval request.

The following example illustrates the most common usage scenario:

>>>importurllib.request>>>local_filename,headers=urllib.request.urlretrieve('http://python.org/')>>>html=open(local_filename)>>>html.close()

If theurl uses thehttp: scheme identifier, the optionaldataargument may be given to specify aPOST request (normally the requesttype isGET). Thedata argument must be a bytes object in standardapplication/x-www-form-urlencoded format; see theurllib.parse.urlencode() function.

urlretrieve() will raiseContentTooShortError when it detects thatthe amount of data available was less than the expected amount (which is thesize reported by aContent-Length header). This can occur, for example, whenthe download is interrupted.

TheContent-Length is treated as a lower bound: if there’s more data to read,urlretrieve reads more data, but if less data is available, it raises theexception.

You can still retrieve the downloaded data in this case, it is stored in thecontent attribute of the exception instance.

If noContent-Length header was supplied, urlretrieve can not check the sizeof the data it has downloaded, and just returns it. In this case you just haveto assume that the download was successful.

urllib.request.urlcleanup()

Cleans up temporary files that may have been left behind by previouscalls tourlretrieve().

classurllib.request.URLopener(proxies=None,**x509)

Deprecated since version 3.3.

Base class for opening and reading URLs. Unless you need to support openingobjects using schemes other thanhttp:,ftp:, orfile:,you probably want to useFancyURLopener.

By default, theURLopener class sends aUser-Agent headerofurllib/VVV, whereVVV is theurllib version number.Applications can define their ownUser-Agent header by subclassingURLopener orFancyURLopener and setting the class attributeversion to an appropriate string value in the subclass definition.

The optionalproxies parameter should be a dictionary mapping scheme names toproxy URLs, where an empty dictionary turns proxies off completely. Its defaultvalue isNone, in which case environmental proxy settings will be used ifpresent, as discussed in the definition ofurlopen(), above.

Additional keyword parameters, collected inx509, may be used forauthentication of the client when using thehttps: scheme. The keywordskey_file andcert_file are supported to provide an SSL key and certificate;both are needed to support client authentication.

URLopener objects will raise anOSError exception if the serverreturns an error code.

open(fullurl,data=None)

Openfullurl using the appropriate protocol. This method sets up cache andproxy information, then calls the appropriate open method with its inputarguments. If the scheme is not recognized,open_unknown() is called.Thedata argument has the same meaning as thedata argument ofurlopen().

This method always quotesfullurl usingquote().

open_unknown(fullurl,data=None)

Overridable interface to open unknown URL types.

retrieve(url,filename=None,reporthook=None,data=None)

Retrieves the contents ofurl and places it infilename. The return valueis a tuple consisting of a local filename and either anemail.message.Message object containing the response headers (for remoteURLs) orNone (for local URLs). The caller must then open and read thecontents offilename. Iffilename is not given and the URL refers to alocal file, the input filename is returned. If the URL is non-local andfilename is not given, the filename is the output oftempfile.mktemp()with a suffix that matches the suffix of the last path component of the inputURL. Ifreporthook is given, it must be a function accepting three numericparameters: A chunk number, the maximum size chunks are read in and the total size of the download(-1 if unknown). It will be called once at the start and after each chunk of data is read from thenetwork.reporthook is ignored for local URLs.

If theurl uses thehttp: scheme identifier, the optionaldataargument may be given to specify aPOST request (normally the request typeisGET). Thedata argument must in standardapplication/x-www-form-urlencoded format; see theurllib.parse.urlencode() function.

version

Variable that specifies the user agent of the opener object. To geturllib to tell servers that it is a particular user agent, set this in asubclass as a class variable or in the constructor before calling the baseconstructor.

classurllib.request.FancyURLopener(...)

Deprecated since version 3.3.

FancyURLopener subclassesURLopener providing default handlingfor the following HTTP response codes: 301, 302, 303, 307 and 401. For the 30xresponse codes listed above, theLocation header is used to fetchthe actual URL. For 401 response codes (authentication required), basic HTTPauthentication is performed. For the 30x response codes, recursion is boundedby the value of themaxtries attribute, which defaults to 10.

For all other response codes, the methodhttp_error_default() is calledwhich you can override in subclasses to handle the error appropriately.

Note

According to the letter ofRFC 2616, 301 and 302 responses to POST requestsmust not be automatically redirected without confirmation by the user. Inreality, browsers do allow automatic redirection of these responses, changingthe POST to a GET, andurllib reproduces this behaviour.

The parameters to the constructor are the same as those forURLopener.

Note

When performing basic authentication, aFancyURLopener instance callsitsprompt_user_passwd() method. The default implementation asks theusers for the required information on the controlling terminal. A subclass mayoverride this method to support more appropriate behavior if needed.

TheFancyURLopener class offers one additional method that should beoverloaded to provide the appropriate behavior:

prompt_user_passwd(host,realm)

Return information needed to authenticate the user at the given host in thespecified security realm. The return value should be a tuple,(user,password), which can be used for basic authentication.

The implementation prompts for this information on the terminal; an applicationshould override this method to use an appropriate interaction model in the localenvironment.

urllib.request Restrictions

  • Currently, only the following protocols are supported: HTTP (versions 0.9 and1.0), FTP, local files, and data URLs.

    Changed in version 3.4:Added support for data URLs.

  • The caching feature ofurlretrieve() has been disabled until someonefinds 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 thefile can’t be opened, the URL is re-interpreted using the FTP protocol. Thiscan sometimes cause confusing error messages.

  • Theurlopen() andurlretrieve() functions can cause arbitrarilylong delays while waiting for a network connection to be set up. This meansthat it is difficult to build an interactive web client using these functionswithout using threads.

  • The data returned byurlopen() orurlretrieve() is the raw datareturned by the server. This may be binary data (such as an image), plain textor (for example) HTML. The HTTP protocol provides type information in the replyheader, which can be inspected by looking at theContent-Typeheader. If the returned data is HTML, you can use the modulehtml.parser to parse it.

  • The code handling the FTP protocol cannot differentiate between a file and adirectory. This can lead to unexpected behavior when attempting to read a URLthat points to a file that is not accessible. If the URL ends in a/, it isassumed to refer to a directory and will be handled accordingly. But if anattempt to read a file leads to a 550 error (meaning the URL cannot be found oris not accessible, often for permission reasons), then the path is treated as adirectory in order to handle the case when a directory is specified by a URL butthe trailing/ has been left off. This can cause misleading results whenyou try to fetch a file whose read permissions make it inaccessible; the FTPcode will try to read it, fail with a 550 error, and then perform a directorylisting for the unreadable file. If fine-grained control is needed, considerusing theftplib module, subclassingFancyURLopener, or changing_urlopener to meet your needs.

urllib.response — Response classes used by urllib

Theurllib.response module defines functions and classes which define aminimal file-like interface, includingread() andreadline().Functions defined by this module are used internally by theurllib.request module.The typical response object is aurllib.response.addinfourl instance:

classurllib.response.addinfourl
url

URL of the resource retrieved, commonly used to determine if a redirect was followed.

headers

Returns the headers of the response in the form of anEmailMessage instance.

status

Added in version 3.9.

Status code returned by server.

geturl()

Deprecated since version 3.9:Deprecated in favor ofurl.

info()

Deprecated since version 3.9:Deprecated in favor ofheaders.

code

Deprecated since version 3.9:Deprecated in favor ofstatus.

getcode()

Deprecated since version 3.9:Deprecated in favor ofstatus.