Python automated testing series [v1.0.0] [handle]

In the actual automated testing process, we often encounter that our products click on the elements in the page, and a new tab of the browser will be launched. Note that the browser tab mentioned here is not a label in our system, but launched. After the second tab of the browser, it means that our automation program has to switch between the two tabs to complete some interactions, so switching tabs has become a problem.

def test_switch_window_handle(self):  # 定义测试方法
	chrome_driver = webdriver.Chrome()  #启动浏览器
	chrome_driver.get("http://www.baidu.com")  #打开百度首页
	baidu_main_handle = chrome_driver.current_window_handle  # 获取当前浏览器句柄 
	print(baidu_main_handle)  # 为方便调试,将句柄打印到控制台 
	time.sleep(5) # 等待5秒
	chrome_driver.find_element_by_link_text("登录").click()  # 点击登录按钮
	time.sleep(5)  # 等待5秒
	chrome_driver.find_element_by_link_text("立即注册").click()  # 在弹出窗口中点击立即注册
	all_handles = chrome_driver.window_handles  # 获取所有句柄
	print(all_handles)  # 打印所有句柄到控制台
	for handle in all_handles: # 在所有句柄中进行循环
        try:
            if handle != baidu_main_handle:  # 判断是否句柄不等于百度首页的句柄,如不等于
                chrome_driver.switch_to.window(handle)  # 则切换句柄 
                print("进入新窗口....")
                chrome_driver.switch_to.window(baidu_main_handle)  #再切换回百度首页句柄
                chrome_driver.refresh() # 刷新页面
			  # 输入检索内容到输入框
                chrome_driver.find_element_by_id("kw").send_keys("__davieyang__") 
                time.sleep(5)
			  # 点击百度一下按钮
                chrome_driver.find_element_by_id("su").click()
                time.sleep(5)
        except Exception as e:
            raise e
	chrome_driver.quit()  # 关闭浏览器
Published 231 original articles · praised 188 · 120,000 views

Guess you like

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