Selenium 2 combat automated test 16 (multi-window switch)

A multi-window switch

During the operation page sometimes click a link will pop up a new window, then you need to switch to a new host open window to operate. WebDriver provides switch_to.window () method. It may be implemented to switch between different windows.
To Baidu and Baidu registration page, for example, to switch between two windows

#coding: UTF-. 8 
from the webdriver Selenium Import 
from selenium.webdriver.common.keys Import Keys 
Import Time 

Driver = webdriver.Chrome () 
driver.implicitly_wait (10) 
driver.get ( "http://www.baidu.com" ) 

# get Baidu search window handle 
search_windows = driver.current_window_handle 

driver.find_element_by_link_text (U "login") .click () 
driver.find_element_by_link_text (U "Register Now") .click () 

# get all currently open windows handle 
all_handles = driver.window_handles 

# to enter the registration window 
for handle in all_handles: 
    ! IF handle = search_windows: 
        driver.switch_to_window (handle) 
        Print '! now the Register window' 
        driver.find_element_by_name ( "userName").send_keys('username') 
        the time.sleep (2) 

# back to the search window
for handle in all_handles:
    if handle==search_windows:
        driver.switch_to_window(handle)
        print 'now search window!'
        driver.find_element_by_id('TANGRAM__PSP_4__closeBtn').click()
        driver.find_element_by_id('kw').send_keys('selenium')
        driver.find_element_by_id('kw').send_keys(Keys.ENTER)
        time.sleep(2)

driver.quit()

 

During script execution: Open the Baidu home page, by current_window_handle get the handle of the current window, and assigned to the variable search_handle . Then open the Log pop, click the "Register Now" on the login pop, thus opening a new registration window. By window_handles get the handle of all currently open windows, and assigned to the variable all_handles .
The first loop through all_handles , if handles are not equal search_handle , then it must be registered window because during script execution only open two windows. Therefore, by switch_to.window () to switch to the page register to register operation. The second cycle is similar to, but this time determines if the handle search_handle equal , then switching to Baidu search page and search operations.
The new method of the present embodiment is directed to:
(. 1) current_window_handle: obtaining the current window handle
(2) window_handles: all windows to return a handle to the current session
(3) switch_to.window (): for switching to the appropriate window, and switch_to. Frame () Similarly, the former is used to switch between different window, which is used to switch between different form.

Guess you like

Origin www.cnblogs.com/Rita-LJ/p/11573676.html