requests登陆后获取的cookies,作为请求头在下一个请求中发送

import requests
import json
from requests.cookies import RequestsCookieJar


# 1、短信验证码
class Denglu():
    @staticmethod
    def send_message(ip="exp"):
        """1、发送短信"""

        url = "http://" + ip + ".123.com/api/sms/send"
        # print(url)
        params = {
            "mobile": "18800000000",
            "type": "1"}
        headers = {'content-type': 'application/json'}

        ret = requests.post(url, data=json.dumps(params), headers=headers)

    def login(self, ip="exp",account="18888888888"):
        """2、点击登陆"""

        self.send_message(ip="exp")
        url = "http://" + ip + ".123.com/api/user/login"

        params = {
            "account": account,
            "code": "123456"}
        headers = {'content-type': 'application/json'}

        ret = requests.post(url, data=json.dumps(params), headers=headers)
        # 获取返回值,解析成json格式的数据
        ret_json = json.loads(ret.text)
        if ret_json["ret"] == 0:
            factor_token = ret_json['data']["tmpToken"]

            return factor_token
        else:
            print(ret_json)

    def login_factor(self, ip="exp"):
        """3、选择保理商角色登陆"""

        #  获取登陆返回的token
        factor_token = self.login(ip="exp")
        url = "http://" + ip + ".123.com/api/user/tmp_login"
        params = {
            "appId": "100006",
            "orgType": 3,
            "tmpToken": factor_token}
        headers = {'content-type': 'application/json'}

        ret = requests.post(url, data=json.dumps(params), headers=headers)
        ret_json = json.loads(ret.text)
        print(ret_json)

        if ret_json["ret"] == 0:
            # 1、通过cookiejar,获取整个cookies的值
            cookies_values = requests.utils.dict_from_cookiejar(ret.cookies)
            print(cookies_values)
            print(type(cookies_values))

            # 2、获取cookies中skey的值
            cookies_skey = cookies_values['skey']

            # 3、重新设置一下cookies
            cookies_jar = RequestsCookieJar()
            cookies_jar.set("skey", cookies_skey)
            print(cookies_jar)
            print(type(cookies_jar))

            return cookies_jar



分成三步走:

  1、通过requests模块导入  from requests.cookies import RequestsCookieJar

  2、进行实例化:jar = RequestsCookieJar()

  3、进行设置: jar.set(cookie['name'], cookie['value'])

requests登陆后获取的cookies,作为请求头在下一个请求中发送_第1张图片

 

你可能感兴趣的:(python自动化测试)