Selenium tool for UI automation testing (browser window switching)

foreword

1. When browsing the web, sometimes clicking a link or button will pop up a new window. This type of window is also called a handle (the unique identifier of a browser window, which enables switching between different browser windows). When we manually control the browser, the browser will automatically help us jump to the latest handle when a new handle is generated (the mouse focuses on the newly opened browser window).

2. In the process of UI automation, the code will not automatically jump to the latest handle by default, and the code needs to switch the handle, that is, switch the browser window.

3. Use the Selenium tool for Web UI automation testing. If the window is not switched when a new window pops up, the focus of the WebDriver object corresponds to the old window, and subsequent automation operations will continue to be performed in the old window. So we need to use code to switch browser windows.

method

Get all window handles of the current browser

handles=driver.window_handles # return value is a list

Explanation: There is a window_handles attribute in the WebDriver object, which returns a list that records all the window handles of the current browser. [handle:; the id of the window corresponding to the browser]

②Switch to the first opened window

driver.switch_to.window(handles[0])

Explanation: If the browser of the UI automation operation has opened multiple windows, the last element of the obtained list is the latest browser window handle.

③Switch to the newly opened window

driver.switch_to.window(handles[-1])

④ Switch to the penultimate open window

driver.switch_to.window(handles[-2])

⑤Get ​​the currently focused browser window handle of the WebDriver object

driver.current_window_handle() 

⑥Verify whether the focus of the WebDriver object is focused on the latest opened browser window

# **先看下当前窗口url地址:**
 print(self.browser.current_url)
    
 # 打印所有的窗口 ['窗口ID1', '窗口ID2', '窗口ID3'] ==> 窗口句柄
 windows = self.browser.window_handles
 print(windows)
    
# 1 切换到最后的窗口
driver.switch_to.window(drivers[-1])
# 切换到最后的窗口后,打印下url,核对下是不是最后的窗口
print(driver.current_url)
 
 2 切换到第二个窗口
 # 先获取现在的窗口
 current_window = self.browser.current_window_handle
    
 # 获取第二个窗口的索引(由当前窗口索引+1)
 next_window_index = windows.index(current_window) + 1
    
 # 切换到第二个窗口
 self.browser.switch_to.window(windows[next_window_index])

 

⑦Selenium tool browser window handle switching API

example

①Example 1

1. Manually open the browser and open Ganji.com: http://bj.ganji.com/, click the recruitment button and you will find a window label on the right.

2. When we use the code to execute the click, we find that there are two windows on the interface, as shown in the figure below, which is the multi-window of the browser.

[Note]: When the browser is manually operated, the effect is two tabs, but two pages appear when the script is executed: (the default script execution does not load any configuration) [manual click is the default way to open a new window in the browser is tabs, and the default way to open a new window in the browser is to appear a new page]

3. Get the window handle of the current browser

①Elements have attributes, and browser windows actually have attributes, but you can’t see them. The attributes of browser windows are identified by handles.

②In the case of manual operation, you can see through your eyes, identify different windows and click to switch. But the script doesn't have eyes, it doesn't know which window you want to operate, at this time it can only be judged by the handle.

③Get the handle method of the current page: driver.current_window_handle 

4. Get all browser handles

① Locate the job application button on Ganji.com and click

② After clicking, get all the current handles: driver.window_handles 

 

5. Switch handle

method one:

    1. Loop to judge whether it is equal to the handle of the home page.

    2. If not, it means the handle of the new page.

    3. After obtaining the new page handle, you can switch to the newly opened page.

    4. Print the title or url of the new page to see if the browser window is switched successfully.

Method Two:

Directly take the last element in the obtained browser handle list, and then switch to this handle id in the code.

6. Close the new window and switch back to the home page 

    1. After opening the new page, I just want to verify that the new page jumps correctly. Here you can do a simple verification to obtain the title verification of the current page

    2. After verification, close the new window

    3. Switch back the handle to the home page

    4. Print the handle of the current page to see if it is switched to the home page

 ②Example 2

#coding = utf-8
 
 
import unittest
from selenium import webdriver
from time import sleep
from selenium.webdriver.common.action_chains import ActionChains
 
 
class Truelogin(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        print("***开始进行登录***")
 
    def setUp(self):
        # 屏蔽自动化受控提示 && 开发者提示
        self.option = webdriver.ChromeOptions()
        self.option.add_experimental_option("excludeSwitches", ['enable-automation', 'load-extension'])
        # 屏蔽'保存密码'提示框
        self.prefs = {}
        self.prefs["credentials_enable_service"] = False
        self.prefs["profile.password_manager_enabled"] = False
        self.option.add_experimental_option("prefs", self.prefs)
        # 打开谷歌浏览器
        self.driver = webdriver.Chrome(options=self.option)
        # 窗口最大化
        self.driver.maximize_window()
        sleep(5)
 
        #打开登录界面
        self.driver.get("ur")
        sleep(5)
    def testcloudAIlogin(self):
        self.driver.switch_to.frame(0)
        self.driver.find_element_by_xpath("//input[@id='username']").send_keys("用户名")
        self.driver.find_element_by_xpath("//input[@id='password']").send_keys("密码*")
        self.driver.find_element_by_xpath("//div[@class='button']/a[@id='loginbtn']").click()
        sleep(5)
        # 获取当前窗口的句柄
        self.window1 = self.driver.current_window_handle
        #搜索框输入系统名称
        self.driver.find_element_by_css_selector("input#search-keyword").send_keys("名称")
        sleep(2)
        ActionChains(self.driver).move_to_element(self.driver.find_element_by_xpath("//a/span[text()='名称']")).perform()
        self.driver.find_element_by_xpath("//a/span[text()='名称']").click()
        sleep(10)
 
        # 获取所有窗口的句柄
        self.all_handles = self.driver.window_handles
        sleep(5)
        #切换到新窗口
        for self.handle in self.all_handles:
            if self.handle != self.window1:
                self.driver._switch_to.window(self.handle)
                print("***这是新窗口***")
        sleep(2)
        self.assertEqual("用户名",self.driver.find_element_by_xpath("//div[text()='用户名']").text)
        sleep(2)
        print("***登录完成***")
 
    def tearDown(self):
        self.driver.quit()
        print("***测试用例结束***")
 
 
    @classmethod
    def tearDownClass(cls):
         print("***一次测试结束***")
 
    if __name__ == '__main__':
        unittest.main()

additional knowledge

After clicking on a page on a web page, a new window is often opened, because the target attribute of the a tag in html is _bank.

Usage of the four parameters of the a tag target attribute target in HTML:

1、target="_self"表示:将链接的画面内容,显示在目前的视窗中。(内定值) 。 即:同窗口打开。
 
2、target="_parent"表示:将链接的画面内容,当成文件的上一个画面。即:当前窗口打开。
 
3、target="_top"表示:将框架中链接的画面内容,显示在没有框架的视窗中(即除去了框架)。即:顶端打开窗口。
 
4、target="_blank"表示:将链接的画面内容,在新的浏览视窗中打开。即:打开新窗口。
 
注意:当网页没有框架时,target="_self"和target="_parent"以及target="_top"三种方式的显示方式几乎相同。

 

Finally, I would like to thank everyone who has read my article carefully. Reciprocity is always necessary. Although it is not a very valuable thing, you can take it away if you need it:

These materials should be the most comprehensive and complete preparation warehouse for [software testing] friends. This warehouse has also accompanied tens of thousands of test engineers through the most difficult journey, and I hope it can help you! Friends in need can click on the small card below to get it  

Guess you like

Origin blog.csdn.net/okcross0/article/details/131811377