• urllib.request —- 用于打开 URL 的可扩展库
    • Request 对象
    • OpenerDirector 对象
    • BaseHandler 对象
    • HTTPRedirectHandler 对象
    • HTTPCookieProcessor 对象
    • ProxyHandler 对象
    • HTTPPasswordMgr 对象
    • HTTPPasswordMgrWithPriorAuth 对象
    • AbstractBasicAuthHandler 对象
    • HTTPBasicAuthHandler 对象
    • ProxyBasicAuthHandler 对象
    • AbstractDigestAuthHandler 对象
    • HTTPDigestAuthHandler 对象
    • ProxyDigestAuthHandler 对象
    • HTTPHandler 对象
    • HTTPSHandler 对象
    • FileHandler 对象
    • DataHandler 对象
    • FTPHandler 对象
    • CacheFTPHandler 对象
    • UnknownHandler 对象
    • HTTPErrorProcessor 对象
    • 示例
    • Legacy interface
    • urllib.request Restrictions
  • urllib.response —- urllib 使用的 Response 类

    urllib.request —- 用于打开 URL 的可扩展库

    源码:Lib/urllib/request.py


    urllib.request 模块定义了适用于在各种复杂情况下打开 URL(主要为 HTTP)的函数和类 —- 例如基本认证、摘要认证、重定向、cookies 及其它。

    参见

    The Requests packageis recommended for a higher-level HTTP client interface.

    urllib.request 模块定义了以下函数:

    • urllib.request.urlopen(url, data=None, [timeout, ]*, cafile=None, capath=None, cadefault=False, context=None)
    • 打开统一资源定位地址 url,可以是一个字符串或一个 Request 对象。

    data must be an object specifying additional data to be sent to theserver, or None if no such data is needed. See Requestfor details.

    urllib.request 模块使用 HTTP/1.1 并且在其 HTTP 请求中包含 Connection:close 头。

    The optional timeout 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.

    If context is specified, it must be a ssl.SSLContext instancedescribing the various SSL options. See HTTPSConnectionfor more details.

    The optional cafile and capath parameters specify a set of trustedCA certificates for HTTPS requests. cafile should point to a singlefile containing a bundle of CA certificates, whereas capath shouldpoint to a directory of hashed certificate files. More information canbe found in ssl.SSLContext.load_verify_locations().

    The cadefault parameter is ignored.

    This function always returns an object which can work as acontext manager and has methods such as

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

    • info() —- return the meta-information of the page, such as headers,in the form of an email.message_from_string() instance (seeQuick Reference to HTTP Headers)

    • getcode() — return the HTTP status code of the response.

    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 the reasonattribute —- 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 and FancyURLopener classes, this functionreturns a urllib.response.addinfourl object.

    协议错误时引发 URLError

    Note that None may be returned if no handler handles the request (thoughthe default installed global OpenerDirector usesUnknownHandler to ensure this never happens).

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

    The legacy urllib.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 to urllib.urlopen, can be obtained by usingProxyHandler objects.

    The default opener raises an auditing eventurllib.Request with arguments fullurl, data, headers,method taken from the request object.

    在 3.2 版更改: 增加了 cafilecapath

    在 3.2 版更改: HTTPS virtual hosts are now supported if possible (that is, ifssl.HAS_SNI is true).

    3.2 新版功能: data 可以是一个可迭代对象。

    在 3.3 版更改: 增加了 cadefault

    在 3.4.3 版更改: 增加了 context

    3.6 版后已移除: cafile, capath and cadefault are deprecated in favor of context.Please use ssl.SSLContext.load_cert_chain() instead, or letssl.create_default_context() select the system's trusted CAcertificates for you.

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

    • urllib.request.buildopener([_handler, ])

    • Return an OpenerDirector instance, which chains the handlers in theorder given. _handler_s can be either instances of BaseHandler, orsubclasses of BaseHandler (in which case it must be possible to callthe constructor without any parameters). Instances of the following classeswill be in front of the _handler_s, unless the _handler_s 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 the ssl modulecan be imported), HTTPSHandler will also be added.

    A BaseHandler subclass may also change its handler_orderattribute to modify its position in the handlers list.

    • urllib.request.pathname2url(path)
    • Convert the pathname path from the local syntax for a path to the form used inthe path component of a URL. This does not produce a complete URL. The returnvalue will already be quoted using the quote() function.

    • urllib.request.url2pathname(path)

    • Convert the path component path from a percent-encoded URL to the local syntax for apath. This does not accept a complete URL. This function usesunquote() to decode path.

    • 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 Mac OSX SystemConfiguration for Mac OS X and Windows Systems Registry for Windows.If both lowercase and uppercase environment variables exist (and disagree),lowercase is preferred.

    注解

    If the environment variable REQUEST_METHOD is set, which usuallyindicates your script is running in a CGI environment, the environmentvariable HTTP_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).

    提供了以下类:

    • class urllib.request.Request(url, data=None, headers={}, origin_req_host=None, unverifiable=False, method=None)
    • This class is an abstraction of a URL request.

    url 应该是是一个含有一个有效的统一资源定位地址的字符串。

    data must be an object specifying additional data to send to theserver, or None if no such data is needed. Currently HTTPrequests are the only ones that use data. The supported objecttypes include bytes, file-like objects, and iterables of bytes-like objects.If no Content-Length nor Transfer-Encoding header fieldhas been provided, HTTPHandler will set these headers accordingto the type of data. Content-Length will be used to sendbytes objects, while Transfer-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 thestandard application/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 the data 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" the User-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; Linux i686) Gecko/20071127 Firefox/2.0.0.11", whileurllib's default user agent string is"Python-urllib/2.6" (on Python 2.6).

    An appropriate Content-Type header should be included if the _data_argument is present. If this header has not been provided and _data_is not None, 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 by RFC 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 by RFC 2965. It defaults to False. 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 by get_method().The default is 'GET' if data is None or 'POST' otherwise.Subclasses may indicate a different default method by setting themethod attribute in the class itself.

    注解

    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. The data is sent to theHTTP server right away after the headers. There is no support fora 100-continue expectation in the library.

    在 3.3 版更改: Request 类增加了 Request.method 参数。

    在 3.4 版更改: Default Request.method may be indicated at the class level.

    在 3.6 版更改: Do not raise an error if the Content-Length has not beenprovided and data is neither None nor a bytes object.Fall back to use chunked transfer encoding instead.

    • class urllib.request.OpenerDirector
    • The OpenerDirector class opens URLs via BaseHandlers chainedtogether. It manages the chaining of handlers, and recovery from errors.

    • class urllib.request.BaseHandler

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

    • class urllib.request.HTTPDefaultErrorHandler

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

    • class urllib.request.HTTPRedirectHandler

    • 一个用于处理重定向的类。

    • class urllib.request.HTTPCookieProcessor(cookiejar=None)

    • 一个用于处理 HTTP Cookies 的类。

    • class urllib.request.ProxyHandler(proxies=None)

    • Cause requests to go through a proxy. If proxies 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 Mac OS X environment proxy informationis retrieved from the OS X System Configuration Framework.

    To disable autodetected proxy pass an empty dictionary.

    The no_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.

    注解

    HTTP_PROXY will be ignored if a variable REQUEST_METHOD is set;see the documentation on getproxies().

    • class urllib.request.HTTPPasswordMgr
    • Keep a database of (realm, uri) -> (user, password) mappings.

    • class urllib.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.

    • class urllib.request.HTTPPasswordMgrWithPriorAuth

    • A variant of HTTPPasswordMgrWithDefaultRealm that also has adatabase of uri -> is_authenticated mappings. Can be used by aBasicAuth handler to determine when to send authentication credentialsimmediately instead of waiting for a 401 response first.

    3.5 新版功能.

    • class urllib.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 with HTTPPasswordMgr; refer to sectionHTTPPasswordMgr 对象 for information on the interface that must besupported. If passwd_mgr also provides is_authenticated andupdate_authenticated methods (seeHTTPPasswordMgrWithPriorAuth 对象), then the handler will use theis_authenticated result for a given URI to determine whether or not tosend authentication credentials with the request. If is_authenticatedreturns True for the URI, credentials are sent. If is_authenticatedis False, credentials are not sent, and then if a 401 response isreceived the request is re-sent with the authentication credentials. Ifauthentication succeeds, update_authenticated is called to setis_authenticated True for the URI, so that subsequent requests tothe URI or any of its super-URIs will automatically include theauthentication credentials.

    3.5 新版功能: 增加了对 is_authenticated 的支持。

    • class urllib.request.HTTPBasicAuthHandler(password_mgr=None)
    • Handle authentication with the remote host. password_mgr, if given, shouldbe something that is compatible with HTTPPasswordMgr; refer tosection HTTPPasswordMgr 对象 for information on the interface that mustbe supported. HTTPBasicAuthHandler will raise a ValueError whenpresented with a wrong Authentication scheme.

    • class urllib.request.ProxyBasicAuthHandler(password_mgr=None)

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

    • class urllib.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 with HTTPPasswordMgr; refer to sectionHTTPPasswordMgr 对象 for information on the interface that must besupported.

    • class urllib.request.HTTPDigestAuthHandler(password_mgr=None)

    • Handle authentication with the remote host. password_mgr, if given, shouldbe something that is compatible with HTTPPasswordMgr; refer tosection HTTPPasswordMgr 对象 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.

    在 3.3 版更改: Raise ValueError on unsupported Authentication Scheme.

    • class urllib.request.ProxyDigestAuthHandler(password_mgr=None)
    • Handle authentication with the proxy. password_mgr, if given, should besomething that is compatible with HTTPPasswordMgr; refer to sectionHTTPPasswordMgr 对象 for information on the interface that must besupported.

    • class urllib.request.HTTPHandler

    • A class to handle opening of HTTP URLs.

    • class urllib.request.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 http.client.HTTPSConnection.

    在 3.2 版更改: context and check_hostname were added.

    • class urllib.request.FileHandler
    • 打开本地文件。

    • class urllib.request.DataHandler

    • Open data URLs.

    3.4 新版功能.

    • class urllib.request.FTPHandler
    • 打开 FTP 统一资源定位地址。

    • class urllib.request.CacheFTPHandler

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

    • class urllib.request.UnknownHandler

    • A catch-all class to handle unknown URLs.

    • class urllib.request.HTTPErrorProcessor

    • Process HTTP error responses.

    Request 对象

    The following methods describe Request'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.

    在 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 the Request uses a proxy, then selectorwill be the full URL that is passed to the proxy.

    • Request.data

    • The entity body for the request, or None if not specified.

    在 3.4 版更改: Changing value of Request.data now deletes "Content-Length"header if it was previously set or calculated.

    • Request.unverifiable
    • boolean, indicates whether the request is unverifiable as definedby RFC 2965.

    • Request.method

    • The HTTP request method to use. By default its value is None,which means that get_method() will do its normal computationof the method to be used. Its value can be set (thus overriding the defaultcomputation in get_method()) either by providing a defaultvalue by setting it at the class level in a Request subclass, or bypassing a value in to the Request constructor via the _method_argument.

    3.3 新版功能.

    在 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 not None, return its value, otherwise return'GET' if Request.data is None, or 'POST' if it's not.This is only meaningful for HTTP requests.

    在 3.3 版更改: get_method now looks at the value of Request.method.

    • Request.addheader(_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 the key 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.

    • Request.addunredirected_header(_key, header)

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

    • Request.hasheader(_header)

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

    • Request.removeheader(_header)

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

    3.4 新版功能.

    • Request.get_full_url()
    • 返回构造器中给定的 URL。

    在 3.4 版更改.

    返回 Request.full_url

    • Request.setproxy(_host, type)
    • Prepare the request by connecting to a proxy server. The host and type willreplace those of the instance, and the instance's selector will be the originalURL given in the constructor.

    • Request.getheader(_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.

    在 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 对象

    OpenerDirector instances have the following methods:

    • OpenerDirector.addhandler(_handler)
    • handler should be an instance of BaseHandler. 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 example httpresponse() wouldbe the HTTP protocol response handler. Also _type should be replaced withthe actual HTTP code, for example http_error_404() would handle HTTP404 errors.

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

    查看 BaseHandler.<protocol>_open() 以获取更多信息。

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

    查看 BaseHandler.httperror<nnn>() 以获取更多信息。

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

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

    查看 BaseHandler.<protocol>_request() 以获取更多信息。

    • <protocol>response() —- signal that the handler knows how topost-process _protocol responses.

    查看 BaseHandler.<protocol>_response() 以获取更多信息。

    • OpenerDirector.open(url, data=None[, timeout])
    • Open the given url (which can be a request object or a string), optionallypassing the given data. Arguments, return values and exceptions raised arethe same as those of urlopen() (which simply calls the open()method on the currently installed global OpenerDirector). Theoptional timeout 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 the httperror<type>()methods of the handler classes.

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

    OpenerDirector objects open URLs in three stages:

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

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

    • 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 return None, the algorithmis repeated for methods named like <protocol>_open(). If all such methodsreturn None, the algorithm is repeated for methods namedunknown_open().

    Note that the implementation of these methods may involve calls of the parentOpenerDirector instance's open() anderror() methods.

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

    BaseHandler 对象

    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.addparent(_director)
    • Add a director as parent.

    • BaseHandler.close()

    • Remove any parents.

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

    注解

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

    • BaseHandler.parent
    • A valid OpenerDirector, which can be used to open using a differentprotocol, or handle errors.

    • BaseHandler.defaultopen(_req)

    • This method is not defined in BaseHandler, 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 the open() of OpenerDirector, or None.It should raise URLError, 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 is not defined in BaseHandler, but subclasses shoulddefine it if they want to handle URLs with the given protocol.

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

    • BaseHandler.unknownopen(_req)
    • This method is not defined in BaseHandler, 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 the parentOpenerDirector. Return values should be the same as fordefault_open().

    • BaseHandler.httperror_default(_req, fp, code, msg, hdrs)
    • This method is not defined in BaseHandler, but subclasses shouldoverride it if they intend to provide a catch-all for otherwise unhandled HTTPerrors. It will be called automatically by the OpenerDirector gettingthe error, and should not normally be called in other circumstances.

    req will be a Request object, fp will be a file-like object withthe 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 mappingobject with the headers of the error.

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

    • BaseHandler.httperror<nnn>(req, fp, code, msg, hdrs)
    • nnn should be a three-digit HTTP error code. This method is also not definedin BaseHandler, but will be called, if it exists, on an instance of asubclass, 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 forhttp_error_default().

    • BaseHandler.<protocol>_request(req)
    • This method is not defined in BaseHandler, but subclasses shoulddefine it if they want to pre-process requests of the given protocol.

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

    • BaseHandler.<protocol>_response(req, response)
    • This method is not defined in BaseHandler, but subclasses shoulddefine it if they want to post-process responses of the given protocol.

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

    HTTPRedirectHandler 对象

    注解

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

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

    • HTTPRedirectHandler.redirectrequest(_req, fp, code, msg, hdrs, newurl)
    • Return a Request or None in response to a redirect. This is calledby the default implementations of the httperror_30() methods when aredirection is received from the server. If a redirection should take place,return a new Request to allow http_error_30() to perform theredirect to _newurl. Otherwise, raise HTTPError ifno other handler should try to handle this URL, or return None if youcan't but another handler might.

    注解

    The default implementation of this method does not strictly follow RFC 2616,which says that 301 and 302 responses to POST 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.httperror_301(_req, fp, code, msg, hdrs)
    • Redirect to the Location: or URI: URL. This method is called by theparent OpenerDirector when getting an HTTP 'moved permanently' response.

    • HTTPRedirectHandler.httperror_302(_req, fp, code, msg, hdrs)

    • The same as http_error_301(), but called for the 'found' response.

    • HTTPRedirectHandler.httperror_303(_req, fp, code, msg, hdrs)

    • The same as http_error_301(), but called for the 'see other' response.

    • HTTPRedirectHandler.httperror_307(_req, fp, code, msg, hdrs)

    • The same as http_error_301(), but called for the 'temporary redirect'response.

    HTTPCookieProcessor 对象

    HTTPCookieProcessor instances have one attribute:

    • HTTPCookieProcessor.cookiejar
    • The http.cookiejar.CookieJar in which cookies are stored.

    ProxyHandler 对象

    • ProxyHandler.<protocol>_open(request)
    • The ProxyHandler will have a method <protocol>open() for every_protocol which has a proxy in the proxies dictionary given in theconstructor. The method will modify requests to go through the proxy, bycalling request.set_proxy(), and call the next handler in the chain toactually execute the protocol.

    HTTPPasswordMgr 对象

    These methods are available on HTTPPasswordMgr andHTTPPasswordMgrWithDefaultRealm objects.

    • HTTPPasswordMgr.addpassword(_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 for realm and a super-URI of any ofthe given URIs is given.

    • HTTPPasswordMgr.finduser_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 HTTPPasswordMgrWithDefaultRealm objects, the realm None will besearched if the given realm has no matching user/password.

    HTTPPasswordMgrWithPriorAuth 对象

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

    • HTTPPasswordMgrWithPriorAuth.addpassword(_realm, uri, user, passwd, is_authenticated=False)
    • realm, uri, user, passwd are as forHTTPPasswordMgr.add_password(). is_authenticated sets the initialvalue of the isauthenticated flag for the given URI or list of URIs.If _is_authenticated is specified as True, realm is ignored.

    • HTTPPasswordMgr.finduser_password(_realm, authuri)

    • Same as for HTTPPasswordMgrWithDefaultRealm objects

    • HTTPPasswordMgrWithPriorAuth.updateauthenticated(_self, uri, is_authenticated=False)

    • Update the isauthenticated flag for the given _uri or listof URIs.

    • HTTPPasswordMgrWithPriorAuth.isauthenticated(_self, authuri)

    • Returns the current state of the is_authenticated flag forthe given URI.

    AbstractBasicAuthHandler 对象

    • AbstractBasicAuthHandler.httperror_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/&#34;). 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 对象

    • HTTPBasicAuthHandler.httperror_401(_req, fp, code, msg, hdrs)
    • Retry the request with authentication information, if available.

    ProxyBasicAuthHandler 对象

    • ProxyBasicAuthHandler.httperror_407(_req, fp, code, msg, hdrs)
    • Retry the request with authentication information, if available.

    AbstractDigestAuthHandler 对象

    • AbstractDigestAuthHandler.httperror_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, req_should be the (failed) Request object, and _headers should be theerror headers.

    HTTPDigestAuthHandler 对象

    • HTTPDigestAuthHandler.httperror_401(_req, fp, code, msg, hdrs)
    • Retry the request with authentication information, if available.

    ProxyDigestAuthHandler 对象

    • ProxyDigestAuthHandler.httperror_407(_req, fp, code, msg, hdrs)
    • Retry the request with authentication information, if available.

    HTTPHandler 对象

    • HTTPHandler.httpopen(_req)
    • Send an HTTP request, which can be either GET or POST, depending onreq.has_data().

    HTTPSHandler 对象

    • HTTPSHandler.httpsopen(_req)
    • Send an HTTPS request, which can be either GET or POST, depending onreq.has_data().

    FileHandler 对象

    • FileHandler.fileopen(_req)
    • Open the file locally, if there is no host name, or the host name is'localhost'.

    在 3.2 版更改: This method is applicable only for local hostnames. When a remotehostname is given, an URLError is raised.

    DataHandler 对象

    • DataHandler.dataopen(_req)
    • Read a data URL. This kind of URL contains the content encoded in the URLitself. The data URL syntax is specified in RFC 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 an ValueError in that case.

    FTPHandler 对象

    • FTPHandler.ftpopen(_req)
    • Open the FTP file indicated by req. The login is always done with emptyusername and password.

    CacheFTPHandler 对象

    CacheFTPHandler objects are FTPHandler objects with thefollowing additional methods:

    • CacheFTPHandler.setTimeout(t)
    • Set timeout of connections to t seconds.

    • CacheFTPHandler.setMaxConns(m)

    • Set maximum number of cached connections to m.

    UnknownHandler 对象

    • UnknownHandler.unknown_open()
    • Raise a URLError exception.

    HTTPErrorProcessor 对象

    • HTTPErrorProcessor.httpresponse(_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 thehttperror<type>() handler methods, via OpenerDirector.error().Eventually, HTTPDefaultErrorHandler will raise anHTTPError if no other handler handles the error.

    • HTTPErrorProcessor.httpsresponse(_request, response)
    • Process HTTPS error responses.

    The behavior is same as http_response().

    示例

    In addition to the examples below, more examples are given inHOWTO 使用 urllib 包获取网络资源.

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

    1. >>> import urllib.request
    2. >>> with urllib.request.urlopen('http://www.python.org/') as f:
    3. ... print(f.read(300))
    4. ...
    5. b'<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    6. "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">\n\n\n<html
    7. xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">\n\n<head>\n
    8. <meta http-equiv="content-type" content="text/html; charset=utf-8" />\n
    9. <title>Python Programming '

    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 W3C document, https://www.w3.org/International/O-charset, liststhe various ways in which an (X)HTML or an XML document could have specified itsencoding information.

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

    1. >>> with urllib.request.urlopen('http://www.python.org/') as f:
    2. ... print(f.read(100).decode('utf-8'))
    3. ...
    4. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    5. "http://www.w3.org/TR/xhtml1/DTD/xhtm

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

    1. >>> import urllib.request
    2. >>> f = urllib.request.urlopen('http://www.python.org/')
    3. >>> print(f.read(100).decode('utf-8'))
    4. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    5. "http://www.w3.org/TR/xhtml1/DTD/xhtm

    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.

    1. >>> import urllib.request
    2. >>> req = urllib.request.Request(url='https://localhost/cgi-bin/test.cgi',
    3. ... data=b'This data is passed to stdin of the CGI')
    4. >>> with urllib.request.urlopen(req) as f:
    5. ... print(f.read().decode('utf-8'))
    6. ...
    7. Got Data: "This data is passed to stdin of the CGI"

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

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

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

    1. import urllib.request
    2. DATA = b'some data'
    3. req = urllib.request.Request(url='http://localhost:8080', data=DATA,method='PUT')
    4. with urllib.request.urlopen(req) as f:
    5. pass
    6. print(f.status)
    7. print(f.reason)

    Use of Basic HTTP Authentication:

    1. import urllib.request
    2. # Create an OpenerDirector with support for Basic HTTP Authentication...
    3. auth_handler = urllib.request.HTTPBasicAuthHandler()
    4. auth_handler.add_password(realm='PDQ Application',
    5. uri='https://mahler:8092/site-updates.py',
    6. user='klem',
    7. passwd='kadidd!ehopper')
    8. opener = urllib.request.build_opener(auth_handler)
    9. # ...and install it globally so it can be used with urlopen.
    10. urllib.request.install_opener(opener)
    11. urllib.request.urlopen('http://www.example.com/login.html')

    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, the http_proxy environment variable is read toobtain the HTTP proxy's URL.

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

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

    Adding HTTP headers:

    Use the headers argument to the Request constructor, or:

    1. import urllib.request
    2. req = urllib.request.Request('http://www.example.com/')
    3. req.add_header('Referer', 'http://www.python.org/')
    4. # Customize the default User-Agent header value:
    5. req.add_header('User-Agent', 'urllib-example/0.1 (Contact: . . .)')
    6. r = urllib.request.urlopen(req)

    OpenerDirector automatically adds a User-Agent header toevery Request. To change this:

    1. import urllib.request
    2. opener = urllib.request.build_opener()
    3. opener.addheaders = [('User-agent', 'Mozilla/5.0')]
    4. opener.open('http://www.example.com/')

    Also, remember that a few standard headers (Content-Length,Content-Type and Host)are added when the Request is passed to urlopen() (orOpenerDirector.open()).

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

    1. >>> import urllib.request
    2. >>> import urllib.parse
    3. >>> params = urllib.parse.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0})
    4. >>> url = "http://www.musi-cal.com/cgi-bin/query?%s" % params
    5. >>> with urllib.request.urlopen(url) as f:
    6. ... print(f.read().decode('utf-8'))
    7. ...

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

    1. >>> import urllib.request
    2. >>> import urllib.parse
    3. >>> data = urllib.parse.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0})
    4. >>> data = data.encode('ascii')
    5. >>> with urllib.request.urlopen("http://requestb.in/xrbl82xr", data) as f:
    6. ... print(f.read().decode('utf-8'))
    7. ...

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

    1. >>> import urllib.request
    2. >>> proxies = {'http': 'http://proxy.example.com:8080/'}
    3. >>> opener = urllib.request.FancyURLopener(proxies)
    4. >>> with opener.open("http://www.python.org") as f:
    5. ... f.read().decode('utf-8')
    6. ...

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

    1. >>> import urllib.request
    2. >>> opener = urllib.request.FancyURLopener({})
    3. >>> with opener.open("http://www.python.org/") as f:
    4. ... f.read().decode('utf-8')
    5. ...

    Legacy interface

    The following functions and classes are ported from the Python 2 moduleurllib (as opposed to urllib2). 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) where filename is thelocal file name under which the object can be found, and headers is whateverthe info() method of the object returned by urlopen() returned (fora remote object). Exceptions are the same as for urlopen().

    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:

    1. >>> import urllib.request
    2. >>> local_filename, headers = urllib.request.urlretrieve('http://python.org/')
    3. >>> html = open(local_filename)
    4. >>> html.close()

    If the url uses the http: scheme identifier, the optional data_argument may be given to specify a POST request (normally the requesttype is GET). The _data argument must be a bytes object in standardapplication/x-www-form-urlencoded format; see theurllib.parse.urlencode() function.

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

    The Content-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 no Content-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 to urlretrieve().

    • class urllib.request.URLopener(proxies=None, **x509)

    3.3 版后已移除.

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

    By default, the URLopener class sends a User-Agent headerof urllib/VVV, where VVV is the urllib version number.Applications can define their own User-Agent header by subclassingURLopener or FancyURLopener and setting the class attributeversion to an appropriate string value in the subclass definition.

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

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

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

    • open(fullurl, data=None)
    • Open fullurl 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.The data argument has the same meaning as the data argument ofurlopen().

    This method always quotes fullurl using quote().

    • openunknown(_fullurl, data=None)
    • Overridable interface to open unknown URL types.

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

    • Retrieves the contents of url and places it in filename. The return valueis a tuple consisting of a local filename and either anemail.message.Message object containing the response headers (for remoteURLs) or None (for local URLs). The caller must then open and read thecontents of filename. If filename 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 of tempfile.mktemp()with a suffix that matches the suffix of the last path component of the inputURL. If reporthook 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 the url uses the http: scheme identifier, the optional data_argument may be given to specify a POST request (normally the request typeis GET). The _data 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.
    • class urllib.request.FancyURLopener()

    3.3 版后已移除.

    FancyURLopener subclasses URLopener providing default handlingfor the following HTTP response codes: 301, 302, 303, 307 and 401. For the 30xresponse codes listed above, the Location 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 the maxtries attribute, which defaults to 10.

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

    注解

    According to the letter of RFC 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, and urllib reproduces this behaviour.

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

    注解

    When performing basic authentication, a FancyURLopener instance callsits prompt_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.

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

    • promptuser_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.

    在 3.4 版更改: Added support for data URLs.

    • The caching feature of urlretrieve() 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.

    • The urlopen() and urlretrieve() 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 by urlopen() or urlretrieve() 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 the _Content-Type_header. 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 the ftplib module, subclassing FancyURLopener, or changing_urlopener to meet your needs.

    urllib.response —- urllib 使用的 Response 类

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