接口获取cookie转换为浏览器能识别的cookie
在Web自动化时,为了提高UI自动化脚本的运行效率,在脚本前后准备好各种数据,可以利用接口自动化将准备条件做好。由此引出的问题是如何保持接口自动化和UI自动化的登陆状态。其本质就是接口自动化的cookie能顺利转成浏览器能识别的cookie。
一、浏览器cookie操作
1、获取cookie
通过以下方式获得浏览器登陆的cookie
driver.get_cookies()
比如获取的cookie如下所示:
[
{
'domain': '192.168.1.1', 'httpOnly': True, 'name': '79e2ac81d96eb0053abba8d3f29f671b', 'path': '/', 'secure': False,'value': '3671e5782657efff5ef732a70c217d77'
},
{
'domain': '192.168.1.1', 'httpOnly': False, 'name': 'userLanguage', 'path': '/163-ui/', 'sameSite': 'Lax','secure': False, 'value': 'zh'
}
]
2、添加cookie
浏览器通过以下方式获得浏览器登陆的cookie
driver.get_cookies()
二、接口请求cookie操作
接口获取页面cookie的方法
response = request.post(url=url,data=data)
cookies = response.cookies._cookies
提取cookie值后
all_cookies = response.cookies._cookies["192.168.1.1"]["/"]
{'79e2ac81d96eb0053abba8d3f29f671b': Cookie(version=0, name='79e2ac81d96eb0053abba8d3f29f671b', value='3671e5782657efff5ef732a70c217d77', port=None, port_specified=False, domain='10.1.17.140', domain_specified=False, domain_initial_dot=False, path='/', path_specified=True, secure=False, expires=None, discard=True, comment=None, comment_url=None, rest={'HttpOnly': None}, rfc2109=False)}
三、转为浏览器能识别的cookie
import time
import requests
from selenium import webdriver
headers = {
"user-agent": "user-agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36",
"content-type": "application/json"
}
def config_options():
options = webdriver.ChromeOptions()
options.add_experimental_option("excludeSwitches", ['enable-automation'])
options.add_argument("--disable-blink-features=AutomationControlled")
options.add_argument('--start-maximized')
options.add_argument('--disable-gpu')
options.add_argument('--ignore-certificate-errors')
return options
class TestOnes:
api_url = "https://ones.ai/project/api/project/auth/login"
url = "https://ones.ai/project/#/auth/login"
target_url = "https://ones.ai/project/#/testcase/team/Ad2j2mn5/index"
json = {"password": "XXX", "email": "XXX@qq.com"}
def setup_class(self):
self.session = requests.session()
self.brower = webdriver.Chrome(chrome_options=config_options())
self.brower.get(self.url)
self.brower.implicitly_wait(5)
def teardown(self):
time.sleep(5)
self.brower.close()
def test_cookie_convert_to_selenium(self):
resp = self.session.post(url=self.api_url, headers=headers, json=self.json, verify=False)
assert resp.status_code == 200
for c in self.session.cookies:
self.brower.add_cookie({'name': c.name, 'value': c.value, 'path': c.path, 'domain': c.domain})
self.brower.refresh()
self.brower.get(self.target_url)
time.sleep(30)
四、封装方法
需要注意的是此方法需要根据实际情况进行修改,具体可以咨询开发人员,系统登陆状态是如何保持的,具体参与有哪些。
def cookie_to_selenium_format(cookie):
"""接口cookie转换为浏览器能识别的cookie"""
cookie_selenium_mapping = {'path': '', 'secure': '', 'name': '', 'value': '', 'expires': ''}
cookie_dict = {}
if getattr(cookie, 'domain_initial_dot'):
cookie_dict['domain'] = '.' + getattr(cookie, 'domain')
else:
cookie_dict['domain'] = getattr(cookie, 'domain')
for k in list(cookie_selenium_mapping.keys()):
key = k
value = getattr(cookie, k)
cookie_dict[key] = value
return cookie_dict