python---cookie
Http is a stateless,so how to record the login information? use Cookie.There are some use of cookie in Python
1.get a cookie object and save it to a variable value
1 import urllib.request 2 import http.cookiejar 3 4 #declare a object to save the cookie 5 cookie = http.cookiejar.CookieJar() 6 #create a cookie processor 7 handler = urllib.request.HTTPCookieProcessor(cookie) 8 #build operer 9 opener = urllib.request.build_opener(handler) 10 response = opener.open('http://www.baidu.com') 11 print(response.getcode()) 12 for item in cookie: 13 print('Name = '+item.name) 14 print('Value = '+item.value)
2.get a cookie and save it to a file
1 import urllib.request 2 import http.cookiejar 3 4 filename = 'cookie.txt' 5 #declare a object to save cookie 6 cookie = http.cookiejar.MozillaCookieJar(filename) 7 #create a cookie processor 8 handler = urllib.request.HTTPCookieProcessor(cookie) 9 #build opener 10 opener = urllib.request.build_opener(handler) 11 response = opener.open('http://www.baidu.com') 12 print (response.getcode()) 13 #write cookie into file named filename 14 cookie.save(ignore_discard=True,ignore_expires=True)
the interpretation of the parameter of save():
ignore_discard: save even cookies set to be discarded.
ignore_expires: save even cookies that have expired.
3.using a cookie saved in a file to visit a web site
1 import urllib.request 2 import http.cookiejar 3 4 cookie = http.cookiejar.MozillaCookieJar() 5 #read cookie from file 6 cookie.load('cookie.txt',ignore_discard=True,ignore_expires=True) 7 req = urllib.request.Request('http://www.baidu.com') 8 opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cookie)) 9 request = opener.open(req) 10 print(request.getcode())