当前位置: 首页 > 工具软件 > VuFind > 使用案例 >

接口自动化之requests学习(六)--获取session,并传到下一个请求中

司空镜
2023-12-01

本次分享一段代码,将获取session的方法和unittest框架相结合

#!usr/bin/env python
#-*- coding:utf-8 -*-
"""
@author:Administrator
@file: requests_post.py
@time: 2018/10/13
"""
import requests
import json
import unittest

class Cookie(unittest.TestCase):
        """练习如何获取cookie"""
        @classmethod
        def setUpClass(cls):
            """登录系统,并将cookie保存在本地文件中"""
            data = {"email": "18791076614",
                    'icode': '',
                    'origURL': 'http://www.renren.com/home',
                    'domain': 'renren.com',
                    'key_id': '1',
                    'captcha_type': 'web_login',
                    'password': '16574db0fa740d05cec88c505f09d59f67081723c18cad5459e60f7a0e240b4e',
                    'rkey': '2565f530e36a171c975a82de7b6c46dc',
                    'f': 'http%3A%2F%2Fzhibo.renren.com%2Ftop'
                    }
            headers = {"Content-Type": "application/x-www-form-urlencoded",
                       "User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36",
                       "Referer": "http://www.renren.com/"}

            url = "http://www.renren.com/ajaxLogin/login?1=1&uniqueTimestamp=2018961914878"

            r = requests.post(url=url, data=data, headers=headers)
            # print(r.text)
            # print(r.cookies)
            #将session保存在本地
            with open('session.txt','w') as f:
                f.write(r.cookies["session"])

        @classmethod
        def tearDownClass(cls):
            pass

        def getSession(self):
            """获取Session"""
            with open('session.txt','r') as f:
                return f.read()

        def test_get_info(self):

            """查看信息"""
            url = "http://webpager.renren.com/api/userGroup"
            r = requests.get(url=url, cookies=self.getSession)
            print(r.text)

if __name__ == '__main__':
        unittest.main(verbosity=1)

 

 类似资料: