欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

获取cookie后,携带cookie请求

程序员文章站 2022-03-02 12:24:39
selenium登录后,获取cookie值,再携带cookie值请求其他的接口set_browser_driver.py 设置浏览器driver(可以设置为静默模式)from selenium import webdriverclass SetBrowserDriver(object): # chrome浏览器设置 def set_chrome_driver(self, headless=False): chrome_options = webdriver.C...

selenium登录后,获取cookie值,再携带cookie值请求其他的接口

set_browser_driver.py 设置浏览器driver(可以设置为静默模式)

from selenium import webdriver


class SetBrowserDriver(object):
    # chrome浏览器设置
    def set_chrome_driver(self, headless=False):
        chrome_options = webdriver.ChromeOptions()
        # 谷歌文档提到需要加上这个规避bug
        chrome_options.add_argument('--disable-gpu')
        # 设置默认编码为utf-8
        chrome_options.add_argument('lang=zh_CN.UTF-8')
        # 取消chrome受自动化软件控制提示
        chrome_options.add_experimental_option('useAutomationExtension', False)
        chrome_options.add_experimental_option("excludeSwitches", ['enable-automation'])

        # 浏览器启用静默模式
        if headless:
            chrome_options.add_argument('headless')

        driver = webdriver.Chrome(chrome_options=chrome_options)
        driver.implicitly_wait(10)  # 隐私等待10秒
        driver.maximize_window()    # 最大化浏览器窗口
        return driver

    # firefox浏览器
    def set_firefox_driver(self):
        driver = webdriver.Firefox()
        driver.implicitly_wait(10)
        driver.maximize_window()
        return driver

set_browser_driver = SetBrowserDriver()

 

浏览器登录tb

selenium_base_page.py

from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.keys import Keys

class BasePage(object):
    # 构造函数
    def __init__(self, driver):
        self.driver = driver

    # 访问页面
    def visit(self, url):
        self.driver.get(url)

    # 关闭浏览器
    def quit(self):
        self.driver.quit()

    # 元素定位
    def locator(self, locator):
        return self.driver.find_element(*locator)

    # 模拟键盘敲回车
    def send_enter(self, locator):
        self.locator(locator).send_keys(Keys.ENTER)

    # 获取元素文本
    def get_text(self, locator):
        return self.locator(locator).text

    # 文本输入框 输入文本
    def input_text(self, locator, input_text):
        self.locator(locator).send_keys(input_text)

    # 点击按钮
    def click_element(self, locator):
        self.locator(locator).click()

    # 判断元素标签是否存在
    def isElementPresent(self, locator):
        try:
            self.locator(locator)
        except NoSuchElementException as e:
            # 发生了NoSuchElementException异常,说明页面中未找到该元素,返回False
            return False
        else:
            # 没有发生异常,表示在页面中找到了该元素,返回True
            return True

 login_page.py

from selenium.webdriver.common.by import By
from time import sleep
from tb_api.utils.selenium_base_page import BasePage
from tb_api.utils.config_util import conf
from tb_api.utils.set_browser_driver import set_browser_driver

# 登录页
class LoginPage(BasePage):
    # 登录页面的元素
    input_username_xpath = (By.XPATH, '//input[contains(@placeholder, "输入手机号")]')
    input_pwd_xpath = (By.XPATH, '//input[@type="password"]')
    click_login_xpath = (By.XPATH, '//button[contains(text(), "立即开始")]')

    # 确认登录页面中的登录按钮
    click_again_login_xpath = (By.XPATH, '//*[@id="root"]/div[1]/div/div[3]/div[2]/button')

    # 确认登录页面中的提示文字
    p_text_xpath = (By.XPATH, '//p[contains(text(), "帐号已登录")]')

    # 登录信息
    login_url = conf.get_browser_login_url
    login_username = conf.get_user_username
    login_pwd = conf.get_user_password

    # 输入登录用户名
    def input_username(self, input_text):
        self.input_text(locator=self.input_username_xpath, input_text=input_text)

    # 输入登录密码
    def input_pwd(self, input_text):
        self.input_text(locator=self.input_pwd_xpath, input_text=input_text)

    # 点击登录按钮
    def click_login(self):
        self.click_element(locator=self.click_login_xpath)

    # 点击登录确认页面中的登录按钮
    def click_again_login(self):
        self.click_element(locator=self.click_again_login_xpath)

    # 登录操作
    def login(self):
        self.visit(self.login_url)
        sleep(1)
        self.input_username(self.login_username)
        self.input_pwd(self.login_pwd)
        self.click_login()
        sleep(3)

    # 账号已登录时,确认登录操作
    def login_again(self):
        if self.isElementPresent(self.p_text_xpath):
            # “账号已登录”文字显示,点击登录确认
            self.click_again_login()
            sleep(1)



if __name__ == '__main__':
    # 浏览器启动
    driver = set_browser_driver.set_chrome_driver()

    # 浏览器登录TB
    lp = LoginPage(driver)
    lp.login()
    # lp.quit()

 

获取cookie值,将cookie值写入ini的配置文件中

from tb_api.page_object.login_page import LoginPage
from tb_api.utils.config_util import conf
from tb_api.utils.set_browser_driver import set_browser_driver


class SetHeaderCookie:
    def set_header_cookie_ini(self):
        print('浏览器登录tb开始……')
        # 浏览器启用静默模式
        driver = set_browser_driver.set_chrome_driver(headless=True)

        # 浏览器登录tb
        login = LoginPage(driver)
        login.login()

        # 写入config_base.ini配置文件,设置cookie值
        cookie_str = self.get_cookie_string(driver)
        print(f'cookie值为:{cookie_str}')
        conf.write_header_cookie(cookie_str)

    # 获取cookie的值
    def get_cookie_string(self, driver):
        cookie = driver.get_cookies()  # 获取cookie键值
        for i in range(0, len(cookie)):
            if cookie[i].get('name') == 'TEAMBITION_SESSIONID':
                tb_session_id = cookie[i].get('value')

            if cookie[i].get('name') == 'TEAMBITION_SESSIONID.sig':
                tb_session_id_sig = cookie[i].get('value')
        cookie_str_format = 'TEAMBITION_SESSIONID={tb_session_id}; TEAMBITION_SESSIONID.sig={tb_session_id_sig}'
        cookie_str = cookie_str_format.replace('{tb_session_id}', tb_session_id).replace('{tb_session_id_sig}', tb_session_id_sig)
        return cookie_str

set_header_cookie = SetHeaderCookie()
if __name__ == '__main__':
    set_header_cookie.set_header_cookie_ini()

config_base.ini  cookie值被设置

[header]
user-agent = Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.75 Safari/537.36
cookie = TEAMBITION_SESSIONID=eyJhdXRoVXBkYXRlZCI6MTYwNzMxMzE4NDQ4MSwibG9naW5Gcm9tIjoidGVhbWJpdGlvbiIsInVpZCI6IjVkYmJjYmQxNTU4YzbmFpbC8xMTFuZWZmZmIwYmMwMzFhNzY4YTU3NTEwMWU1NTBlMjk1OTUvdy8yMDAvaC8yMDAiLCJyZWdpb24iOiJjbiIsImxhbmciOiIiLCJpc1JvYm90IjpmYWxzZSwib3BlbklkIjoiIiwicGhvbmVGb3JMb2dpbiI6IjE1OTAwNzIyMzQ0In19; TEAMBITION_SESSIONID.sig=51wS-95WgCoopmjsRmqmOs0eG0U

再做其他接口请求时,携带该cookie值(请求的header中增加cookie)

import os
import requests
from tb_api.utils.config_util import conf
from datetime import timedelta, datetime

class Base(object):
    header = {
        'User-Agent': conf.get_header_user_agent,
        'cookie': conf.get_header_cookie
    }
    session = requests.session()

    def get_session(self, url, param=None):
        res = self.session.get(url=url, headers=self.header, params=param)
        res.encoding = 'utf-8'
        return res

    def post_session(self, url, data=None):
        res = self.session.post(url=url, headers=self.header, data=data)
        res.encoding = 'utf-8'
        return res

    def request_session(self, url, method, data=None):
        res = None
        if method.upper() == 'GET':
            res = self.get_session(url, param=data)
        elif method.upper == 'POST':
            res = self.post_session(url, data=data)
        else:
            print("未定义过的方法,请检查代码。")
        return res

    def close_session(self):
        self.session.close()

    # 请求url中的关键字替换
    def replace_id(self, str, project_id, smartgroups_id="", task_id=""):
        return str.replace('{project_id}', project_id).\
            replace('{smartgroups_id}', smartgroups_id).\
            replace('{task_id}', task_id)

    # 格林威治时间转为北京时间
    def utc_to_bjs(self, utc_time):
        if utc_time:
            utc_format = "%Y-%m-%dT%H:%M:%S.%fZ"
            bjs_format = "%Y-%m-%d %H:%M:%S"
            utc = datetime.strptime(utc_time, utc_format)
            # 格林威治时间+8小时变为北京时间
            bjs = utc + timedelta(hours=8)
            bjs = bjs.strftime(bjs_format)
            return bjs

    def file_to_list(self, file_path):
        with open(file_path, 'r', encoding='utf-8') as fp:
            lines = fp.readlines()
            for line in lines:
                line_index = lines.index(line)
                lines[line_index] = line.strip('\n')
        return lines

    def create_dir(self, dir_path):
        if not os.path.exists(dir_path):
            os.mkdir(dir_path)

 

本文地址:https://blog.csdn.net/nikeylee/article/details/110871996

相关标签: 自动化测试