Python Automated Test Series [v1.0.0] [Processing Cookies]

In some scenarios, it is necessary to process browser cookies. For example, you can often see that some websites provide a consultation window inside the page. Click the window to talk to the customer service. However, when talking to the customer service for the first time, the customer service side The name of the displayed conversation is assumed to be visitor A. When the site is opened again after half an hour to continue chatting, the customer service side will still display visitor A. However, if the cookie is cleared, after opening the website to talk to customer service, the customer service side shows that we may be New visitors.
The author just cites a common scenario of an Internet product system. If this scenario requires automated testing, we will undoubtedly master the method of handling cookies. In this section, I will introduce the method of encapsulating operation cookies and how to use the encapsulated method Handle cookies.

Method encapsulation

def delete_current_cookie(self):  # 封装删除当前所有cookie的方法
    """
    删除所有cookie
    :return:
    """
    self.driver.delete_all_cookies()
def get_current_cookies(self):  # 封装获取当前cookies的方法
    """
    获取当前cookies
    :return:
    """
    current_cookie = self.driver.get_cookies()
    return current_cookie
def get_current_cookie_value(self, key):  # 获取当前name为key的cookie信息
    """
    获取key为key的cookie信息
    :param key:
    :return:
    """
    key_cookie = self.driver.get_cookie(key)
    return key_cookie
def add_key_value_to_cookie(self, cookie_dict):  # 添加cookie,参数为字典
    """
    添加cookie
    :return:
    """
    self.driver.add_cookie(cookie_dict)

Method call

Then look at how to call it, add the following test method in the test_advanced_application file to verify whether the encapsulated method is available, the code is shown below.

def test_cookies(self):  # 定义新的测试方法
    cookie_dict = {'name': 'name_yang', 'value': 'cookie_yang'}  # 定义字典 
    chrome_driver = webdriver.Chrome()  # 启动浏览器
    chrome_driver.get("https://www.baidu.com")
    time.sleep(10)
	# 获取当前所有cookie
    current_cookie = Browser_Controller(chrome_driver).get_current_cookies()
    # 打印当前cookie
	print(current_cookie)
    # 将之前定义的字典添加到cookie中去
	Browser_Controller(chrome_driver).add_key_value_to_cookie(cookie_dict)
    # 获取name为name_yang的cookie信息
	key_cookie = Browser_Controller(chrome_driver).get_current_cookie_value('name_yang')
    # 打印cookie信息
	print(key_cookie)
    # 删除当前cookie
	Browser_Controller(chrome_driver).delete_current_cookie()
    # 删除后再次获取cookie
	current_cookie_2 = Browser_Controller(chrome_driver).get_current_cookies()
    # 将当前cookie转换成字符串打印到控制台
	print(str(current_cookie_2) + "只有这几个字没有cookie了")
Published 231 original articles · praised 188 · 120,000 views

Guess you like

Origin blog.csdn.net/dawei_yang000000/article/details/105648281