Two important concepts in urllib2: Openers, Handlers, and urllib2openers

Source: Internet
Author: User

Two important concepts in urllib2: Openers, Handlers, and urllib2openers

Before starting the following content, let's first explain the two methods in urllib2: info/geturl
The response object response (or HTTPError instance) returned by urlopen has two useful methods: info () and geturl ()

1. geturl ():

This returns the obtained real URL, which is useful because urlopen (or used by the opener object) may be redirected. The obtained URL may be different from the requested URL.
Take a hyperlink from a person as an example,
We will create a urllib2_test10.py file to compare the original URL with the redirection link:

Copy codeThe Code is as follows:
From urllib2 import Request, urlopen, URLError, HTTPError
Old_url = 'HTTP: // rrurl.cn/b1UZuP'
Req = Request (old_url)
Response = urlopen (req)
Print 'old url: '+ old_url
Print 'real url: '+ response. geturl ()

After running the command, you can see the URL that the real link points:

2. info ():

The dictionary object of the returned object, which describes the page information obtained. It is usually the specific headers sent by the server. Currently, this is an httplib. HTTPMessage instance.
The classic headers include "Content-length", "Content-type", and other Content.
We will create a urllib2_test11.py to test the info application:

Copy codeThe Code is as follows:
From urllib2 import Request, urlopen, URLError, HTTPError
Old_url = 'HTTP: // www.baidu.com'
Req = Request (old_url)
Response = urlopen (req)
Print 'info ():'
Print response.info ()

The running result is as follows:

The following describes two important concepts in urllib2: Openers and Handlers.

1. Openers:

When you get a URL, you use an opener (an instance of urllib2.OpenerDirector ).
Normally, we use the default opener: urlopen.
But you can create personalized openers.

2. Handles:

Openers uses the processor handlers, and all the "heavy" Work is handled by handlers.
Each handlers knows how to enable URLs through a specific protocol, or how to handle various aspects of URL opening.
For example, HTTP redirection or HTTP cookies.

If you want to use a specific processor to obtain URLs, you will want to create an openers, such as an opener that can process cookies or an opener that does not redirect.

To create an opener, You Can instantiate an OpenerDirector,
Call. add_handler (some_handler_instance ).
Similarly, you can use build_opener, which is a more convenient function used to create opener objects. He only needs to call the handler function.
Build_opener adds several processors by default, but provides a quick way to add or update the default processor.
Other Processors handlers you may want to process proxy, verification, and other commonly used but a little special.

Install_opener is used to create (global) default opener. This indicates that calling urlopen will use the opener you installed.
The Opener object has an open method.
This method can be directly used to obtain urls like the urlopen function: you do not need to call install_opener, except for convenience.

After completing the above two content, let's take a look at the Basic Authentication content. Here we will use the Opener and Handler mentioned above.

Basic Authentication

To demonstrate how to create and install a handler, we will use HTTPBasicAuthHandler.
When basic verification is required, the server sends a header (401 error code) request for verification. This specifies scheme and a 'realm', which looks like this: Www-authenticate: SCHEME realm = "realm ".
For example
Www-authenticate: Basic realm = "cPanel Users"
The client must use a new request and contain the correct name and password in the request header.
This is "basic verification". To simplify this process, we can create an HTTPBasicAuthHandler instance and let opener use this handler.

HTTPBasicAuthHandler uses a password management object to process URLs and realms to map user names and passwords.
If you know what realm is, you can use HTTPPasswordMgr.

Usually people don't care what realm is. In this way, you can use the convenient HTTPPasswordMgrWithDefaultRealm.
This will specify a default user name and password for the URL.
This will be provided when you provide another combination for a specific realm.
We specify None for the realm parameter and provide it to add_password to indicate this situation.

The URL at the highest level is the first URL that requires verification. The deeper URLs you pass to. add_password () will be the same.
After talking about so much nonsense, let's use an example to demonstrate the content mentioned above.
We will create a urllib2_test12.py to test the info application:

Copy codeThe Code is as follows:
#-*-Coding: UTF-8 -*-
Import urllib2
# Create a Password Manager
Password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm ()
# Add a user name and password
Top_level_url = "http://example.com/foo"
# If we know realm, we can use it instead of ''non ''.
# Password_mgr.add_password (None, top_level_url, username, password)
Password_mgr.add_password (None, top_level_url, 'why', '123 ')
# Create a new handler
Handler = urllib2.HTTPBasicAuthHandler (password_mgr)
# Create an "opener" (OpenerDirector instance)
Opener = urllib2.build _ opener (handler)
A_url = 'HTTP: // www.baidu.com /'
# Use opener to obtain a URL
Opener. open (a_url)
# Install opener.
# Now all calls to urllib2.urlopen will use our opener.
Urllib2.install _ opener (opener)


Note: In the preceding example, we only provide our HHTPBasicAuthHandler to build_opener.
The default openers have normal handlers: ProxyHandler, UnknownHandler, HTTPHandler, HTTPDefaultErrorHandler, HTTPRedirectHandler, FTPHandler, FileHandler, and HTTPErrorProcessor.
The top_level_url in the code can be a complete URL (including "http:" and the host name and the optional port number ).
For example, http://example.com /.
It can also be an "authority" (that is, the host name and the optional include port number ).
For example, "example.com" or "example.com: 8080 ".
The latter contains the port number.




Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.