Python3发送post请求,自动记住cookie

在做登录的post请求时,需要记住cookie,否则不能访问登录后的页面。

下面是登录的代码:

#coding:utf-8
import urllib
import http.cookiejar

url = "http://c.highpin.cn/Users/CLogin"
postdata =urllib.parse.urlencode({
"Logon_Password":"sunmin",
"Logon_PostCode":"fghc",
"Logon_RememberMe":"false",
"Logon_UserEmail":"[email protected]"
}).encode('utf-8')
header = {
"Accept":"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
"Accept-Encoding":"utf-8",
"Accept-Language":"zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3",
"Connection":"keep-alive",
"Host":"c.highpin.cn",
"Referer":"http://c.highpin.cn/",
"User-Agent":"Mozilla/5.0 (Windows NT 6.1; WOW64; rv:32.0) Gecko/20100101 Firefox/32.0"
}
req = urllib.request.Request(url,postdata,header)
##print(urllib.request.urlopen(req).read().decode('utf-8'))

#自动记住cookie
cj = http.cookiejar.CookieJar()
opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj))
r = opener.open(req)
print(r.read().decode('utf-8'))

以前用的是python2.7,但是python3开始很多包的位置和以前不一样了,就对这里用到的说明一下:

urllib2合并到了urllib下,urlopen使用时包的位置为urllib.request.urlopen,urlencode使用包位置为urllib.parse.urlencode

cookielib变更为了http.cookiejar

 

说明:带cookie的打印出来必须用opener.open(req).read().decode('utf-8')来发送的请求才会带上cookie,如果用urllib.request.urlopen()是不带cookie的

 

Python3和Python2的变更,可以参考文章:http://blog.csdn.net/samxx8/article/details/21535901    

你可能感兴趣的:(python3)