redmine使用post登录,cookie使用

import re
import requests

# 基础url
url = "http://192.168.200.180"
# 登录url
loginurl = url + "/redmine/login"
# 通过登录页面获取登录需要的Cookie
rs = requests.get(loginurl)
print(rs.headers['Set-Cookie'])
pagesource = rs.text
Cookie = rs.headers['Set-Cookie']

# 通过正则在登录页面内解析出登录需要的authenticity_token
pattern = re.compile(u'<input type="hidden" name="authenticity_token" value="(.*?)" />',re.S)
match = re.findall(pattern,pagesource)
# print(match[0])
authenticity_token = match[0]
# 登录参数
values = {'utf8':'',
          'authenticity_token':authenticity_token,
          'back_url':'http://192.168.200.180/redmine/',
          'username':'jint',
          'password':'123456',
          'login':'登录 »'}
# 请求头,从登录前开始,每次发送请求都需要从上一次response的Set-Cookie内获得下一次请求的Cookie
headers = {"Accept":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
           "Content-Type":"application/x-www-form-urlencoded",
           "Accept-Encoding":"gzip, deflate",
           "Accept-Language":"zh-CN,zh;q=0.8",
           "Host":"192.168.200.180",
           "Upgrade-Insecure-Requests":"1",
           "Connection":"Keep-Alive","Referer":"http://192.168.200.180/redmine/",
           "User-Agent":"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36",
           "Cookie":Cookie}

# post方式提交登录表格,返回一个response对象
r = requests.post(loginurl,data=values,headers=headers)
# print(r.headers["Date"])
# print(r.headers["Connection"])
print(r.headers["Set-Cookie"])
print(r.status_code)
print(r.url)
# print(r.text)
# 从返回的response对象内获取下一次请求需要用到的Session Cookie
Cookie = r.headers["Set-Cookie"]
# 去掉Cookie内的无效后缀
pos = Cookie.find(";")
Cookie = Cookie[0:pos]
# print(Cookie)
# 登录成功后,下一个页面请求开始
headers["Cookie"] = Cookie
mypage = url + "/redmine/my/page"
r1 = requests.get(mypage,headers=headers)
print(r1.status_code)
print(r1.url)
# 页面内容
# print(r1.text)

# 继续请求下一个页面
mp = url + "/redmine/projects/mp/issues"
Cookie = r1.headers["Set-Cookie"]
pos = Cookie.find(";")
Cookie = Cookie[0:pos]
headers["Cookie"] = Cookie
r2 = requests.get(mp,headers=headers)
print(r2.status_code)
print(r2.url)
原文地址:https://www.cnblogs.com/ylsd80/p/7235565.html