Python3发送post请求,自动记住cookie
1 #coding:utf-8 2 import urllib 3 import http.cookiejar 4 5 url = "http://c.highpin.cn/Users/CLogin" 6 postdata =urllib.parse.urlencode({ 7 "Logon_Password":"sunmin", 8 "Logon_PostCode":"fghc", 9 "Logon_RememberMe":"false", 10 "Logon_UserEmail":"sun121@qq.com" 11 }).encode('utf-8') 12 header = { 13 "Accept":"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8", 14 "Accept-Encoding":"utf-8", 15 "Accept-Language":"zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3", 16 "Connection":"keep-alive", 17 "Host":"c.highpin.cn", 18 "Referer":"http://c.highpin.cn/", 19 "User-Agent":"Mozilla/5.0 (Windows NT 6.1; WOW64; rv:32.0) Gecko/20100101 Firefox/32.0" 20 } 21 req = urllib.request.Request(url,postdata,header) 22 ##print(urllib.request.urlopen(req).read().decode('utf-8')) 23 24 #自动记住cookie 25 cj = http.cookiejar.CookieJar() 26 opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj))
urllib.request.install_opener(opener)# 安装opener到全局 27 r = opener.open(req) 28 print(r.read().decode('utf-8'))
Session操作
import requests loginurl = 'http:xx.com/login' s = requests.Session() r = s.get(loginurl,allow_Redirects = True) data = {'name':'xxx','pwd':'xxx'} r = s.post(loginurl,data=data,allow_Redirects = True) print(r.text)