Python Processing cookies detailed _python

Source: Internet
Author: User

To install the Cookie,http server in the user's browser, add an HTTP header that resembles the following in the HTTP response:

Copy Code code as follows:

set-cookie:session=8345234;expires=sun,15-nov-2013 15:00:00 gmt;path=/;domain=baidu.com

Expires is the lifetime of a cookie, path is a valid path for cookies, and domain is a valid domain for cookies.

Path "path" is used to set the topmost directory where a cookie can be read.

Setting the path of the cookie to the top-most directory of your Web page allows the cookie to be accessible to all pages in that directory.

Method: Add path=/to your cookie; If you only want the page in the "Food" directory to be able to use the cookie, then you join Path=/food;

Domain: Some sites have many small domain names, such as Baidu may also be "news.baidu.com" "zhidao.baidu.com" and "v.baidu.com" under the Domain Name page.

If you want all machines under "baidu.com" to read the cookie, you must include "domain=.baidu.com" in the cookie.

The user's browser stores cookies until they expire, and the browser sends an HTTP request header similar to the following for servers that match path and domain:

Copy Code code as follows:

cookie:session=8345234.

For example, when landing www.baidu.com, the HTTP response header sent back by the Baidu server is a cookie:

Copy Code code as follows:

set-cookie:h_ps_pssid=4681_4567_1452_9876_4759; path=/; Domain=.baidu.com
set-cookie:bdsvrtm=74; path=/

HTTP request header for the browser:

Copy Code code as follows:

cookie:baiduid=0fd996sdfg12********107b9c227f4c:fg=1; Locale=zh; bdshare_firstime=1384567418140; nbid=d830dd2345hh2818a9f4134e5a2d778d3b:fg=1; h_ps_lc=4_shadu2014; Bd_ck_sam=1; h_ps_pssid=4681_4567_1452_9876_4759

When the browser sends the cookie back to the HTTP server, it uses the encoding form of the Key=value string and does not return optional attributes such as Expires,path and domain.

The cookie string is usually located in the HTTP_COOKIE environment variable and can be read as follows:

Copy Code code as follows:

Import OS
Print "content-type:text/plain\n"
If "Http_cookie" in Os.environ:
Print os.environ["Http_cookie"]
Else
Print "Http_cookie not set!"

The cookie module in Python (http.cookies in Python2,python3) provides a dictionary-like special object Simplecookie that stores and manages a collection of cookie values called morsel.

Each morsel has name,value and optional attributes (expires,path,domain,comment,max-age,secure,version,httponly).

Simplecookie can use the output () method to create a cookie data output in the form of an HTTP header, using the Js_output () method to generate a string that contains JavaScript code.

To generate cookies with Http_cookie:

Copy Code code as follows:

Cookie=cookie.simplecookie (os.environ[' Http_cookie ')
Print Cookie.output ()

Set Cookie:

Copy Code code as follows:

Import Cookie
Import datetime
Import Random

Expiration = Datetime.datetime.now () + Datetime.timedelta (days=30)
Cookie = Cookie.simplecookie ()
cookie["Session" = Random.randint (1,1000000000)
cookie["Session" ["domain"] = ". Baidu.com"
cookie["Session" ["path"] = "/"
cookie["Session" ["Expires"] = Expiration.strftime ("%a,%d-%b-%y%h:%m:%s PST")

Print "Content-type:text/plain"
Print Cookie.output ()
Print
Print "Cookie set with:" + cookie.output ()

Output:

Copy Code code as follows:

Content-type:text/plain
set-cookie:session=155209565; domain=.jayconrod.com; Expires=mon, 03-mar-2014 07:42:47 PST; path=/
Cookie set with:set-cookie:session=155209565; domain=.jayconrod.com; Expires=mon, 03-mar-2014 07:42:47 PST; path=/

The Cookielib library in Python (Http.cookiejar in Python3) provides client support for storing and managing cookies.

The main function of this module is to provide objects that can store cookies. Use this module to capture cookies and resend them on subsequent connection requests, and to

Processes files that contain cookie data.

This module mainly provides these objects, Cookiejar,filecookiejar,mozillacookiejar,lwpcookiejar.

The Cookiejar object is stored in memory.

Copy Code code as follows:

>>> Import Urllib2
>>> Import Cookielib
>>> Cookie=cookielib. Cookiejar ()
>>> Handler=urllib2. Httpcookieprocessor (Cookie)
>>> Opener=urllib2.build_opener (handler)
>>> opener.open (' http://www.google.com.hk ') <addinfourl at 161806444 whose fp = <socket._fileobject Object at 0x9a348ac>>

Access to Google cookies has been captured.

Look at what it is:

Copy Code code as follows:

>>> Print Cookies
<cookielib. Cookiejar[<cookie Nid=67=b6yqoeiejcqdj-adada_wmnyl_ JVADSDEDCHFTMTAGERTGRJK452KO6GR9G0Q5P9H1VLMHPCR56XCRWWG1PV6IQHZNAVLNWOEM-LN7KIUWI92L-X2FVUQGWDNN3QOWDW for. Google.com.hk/>, <cookie PREF=ID=7AE0FA51234CE2B1:FF=0:NW=1:TM=1391219446:LM=1391219446:S=CFIZ5X8TS9NY3CMK For .google.com.hk/>]>

Appears to be a collection of cookie instances with properties such as Name,value,path,expires:

Copy Code code as follows:

>>> for CK in Cookie:
... print ck.name, ': ', Ck.value
...
Nid:67=b6yqoeiejcqdj-adada_wmnyl_ Jvadsdedchftmtagertgrjk452ko6gr9g0q5p9h1vlmhpcr56xcrwwg1pv6iqhznavlnwoem-ln7kiuwi92l-x2fvuqgwdnn3qowdw
Pref:id=7ae0fa51234ce2b1:ff=0:nw=1:tm=1391219446:lm=1391219446:s=cfiz5x8ts9ny3cmk

You can also capture cookies to a file.

Filecookiejar (filename)

Create a Filecookiejar instance, retrieve cookie information and store the information in a file, filename is the filename.

Mozillacookiejar (filename)

Create a Filecookiejar instance that is compatible with the Mozilla Cookies.txt file.

Lwpcookiejar (filename)

Create a Filecookiejar instance that is compatible with the Libwww-perl set-cookie3 file.

Code:

Copy Code code as follows:

Import Urllib2
Import Cookielib
Def Handlecookie ():
#handle Cookie whit file
Filename= ' FileCookieJar.txt '
Url= ' http://www.google.com.hk '
Filecookiejar=cookielib. Lwpcookiejar (filename)
Filecookejar.save ()
Opener =urllib2.build_opener (Urllib2. Httpcookieprocessor (Filecookiejar))
Opener.open (URL)
Filecookiejar.save ()
Print open (filename). Read ()
#read Cookie from File
Readfilename = "ReadFileCookieJar.txt"
Mozillacookiejarfile =cookielib. Mozillacookiejar (Readfilename)
Print Mozillacookiejarfile
Mozillacookiejarfile.load (Cookiefilenamemozilla)
Print Mozillacookiejarfile
If __name__== "__main__":
Handlecookie ()

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.