How to use the cookielib module to operate cookies in Python

Source: Internet
Author: User
The cookielib module is often used to work with urllib and other modules to create crawlers or third-party SNS clients. for example, here we will use cookies to send logon information to log on to Renren, well, let's take a look at the example tutorial of using the cookielib module to operate cookies in Python. cookielib is a module that automatically processes cookies. if we need to save cookies when using crawler and other technologies, cookielib will help you get twice the result with half the effort! His most common partner modules are urllib and request in python.

Core
1. Cookie
This class implements the cookie standard defined by Netscape and RFC 2965 cookies, which can basically be understood as a piece of cookie data.
Some code is as follows. are many attributes familiar?

    self.domain_initial_dot = domain_initial_dot    self.path = path    self.path_specified = path_specified    self.secure = secure    self.expires = expires    self.discard = discard    self.comment = comment    self.comment_url = comment_url    self.rfc2109 = rfc2109

2. CookiePolicy
The main function of this class is to send and receive cookies, that is, ensure that the correct cookie is sent to the corresponding domain name, and vice versa.
3. defacookcookiepolicy
This class implements the CookiePolicy interface.
4. CookieJar
CookieJar is a set of cookies. it can contain many cookie classes and is our main operation object. There are a series of methods to support more detailed operations!
5. FileCookieJar
This class inherits from CookieJar. CookieJar only completes its own lifecycle in the memory. the FileCookieJar subclass can realize data persistence and defines three interfaces: save, load, and revert.
6. MozillaCookieJar & LWPCookieJar
The inheritance relationships between the two implementation classes are as follows:

Instance: log on to Renren
Using httpFox plug-in firefox to find Renren login requires POST address is http://www.renren.com/ajaxLogin

In addition, we can see that the DATA to be POST has email and password.
Python uses cookielib to process cookies. The following is a simple code:

>>> import urllib>>> import urllib2,cookielib>>> login_page = "http://www.renren.com/ajaxLogin">>> cj = cookielib.CookieJar()>>> opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))>>> opener.add_handler = [('User-agent','Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)')]>>> data = urllib.urlencode({"email":'username',"password":'password'}) >>> opener.open(login_page,data)>>>> if cj:... for index,cookie in enumerate(cj):...  print index,':',cookie...  0 : 
 1 : 
 2 : 
 3 : 
 4 : 
 5 : 
 6 : 
 7 : 
 8 : 
 9 : 
 10 : 
 11 : 
 >>>

It can be compared with the cookie obtained in firebug or httpFox. The value may be different, but the key is basically the same. each login should be different.

I also tried to use fidder to simulate sending POST data without a cookie, but I didn't get the desired return value.

After adding the cookie information, you can jump to your home page.

Okay. I basically learned how to use cookies to send logon information in python. now let's write a small script to log on to the Internet.

# Encoding = utf-8import urllib2import urllibimport cookielibdef renrenrenbrower (url, user, password): login_page = "http://www.renren.com/ajaxLogin" try: cj = cookielib. cookieJar () opener = urllib2.build _ opener (urllib2.HTTPCookieProcessor (cj) opener. addheaders = [('User-agent', 'mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1) ')] data = urllib. urlencode ({"email": user, "password": password}) opener. open (login_page, data) op = opener. open (url) data = op. read () return data partition T Exception, e: print str (e) print renrenBrower ("http://www.renren.com/home", "username", "password ")

In this way, you can display the information on your homepage. In fact, after logging on, you can also write scripts to get the information you want, such as new things of friends, I won't explain much here ~

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.