python接口自动化-post请求2

一、headers

1.以禅道登录为例,模拟登陆,这里需添加请求头headers,可以用fiddler抓包

 

2.将请求头写成字典格式

  h = {
        "Connection": "keep-alive",
        "Content-Length": "155",
        "Cache-Control": "max-age=0",
        "Content-Type": "application/x-www-form-urlencoded",
        "User-Agent": "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36",
        "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
        "Referer": "http://127.0.0.1/biz/user-login.html",
        "Accept-Encoding": "gzip, deflate, br",
        "Accept-Language": "zh-CN,zh;q=0.9",
        # "Cookie":  头部没登录前不用传cookie,因为这里cookie就是保持登录的
        }

 

二、禅道登录实操

#coding:utf-8
import requests
host = "http://127.0.0.1"
def login(s,username,psw):
    url = host+"/zentao/user-login.html"
    h = {
        "Connection": "keep-alive",
        "Cache-Control": "max-age=0",
        "Content-Type": "application/x-www-form-urlencoded",
        "User-Agent": "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36",
        "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
        "Referer": host + "/biz/user-login.html",
        "Accept-Encoding": "gzip, deflate, br",
        "Accept-Language": "zh-CN,zh;q=0.9",
        # "Cookie":  头部没登录前不用传cookie,因为这里cookie就是保持登录的
        }

    body = { "account": username,
             "password": psw,
             "keepLogin[]": "on",
             "referer":  host+"/biz/bug-browse-1-0-unclosed-0-id_desc.html",
             "verifyRand": "189433841"
            }

    r = s.post(url, data=body, headers=h)
    return r.content.decode("utf-8")  # python3

def is_login_sucess(res):
        if "登录失败,请检查您的用户名或密码是否填写正确。" in res:
                return False
        elif "parent.location=" in res:
                return True
        else:
                return False

if __name__ == "__main__":
    s = requests.session()
    a = login(s, "admin", "051e0ceb320dedbd2b34f0230d8b465b")
    result = is_login_sucess(a)
    print("测试结果:%s"%result)

  

 注:登录未成功,body 中 多了 "verifyRand": "189433841"  ,参数 verifyRand 是实时变化的,如果是在工作中可以让研发固定这个值或测试时暂时取消这个值,灵活沟通。

转载于:https://www.cnblogs.com/JodieRao/p/10588410.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值