Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

Selenium Learning: multi-window switching

Shulou Source: shulou.com Published: 2022-06-02 19:36:51 10月28日 Update

File name: test12.py

From selenium import webdriverimport timedriver = webdriver.Chrome () file_path=' http://www.baidu.com'driver.get(file_path)# get Baidu search window handle search_windows=driver.current_window_handledriver.find_element_by_link_text ('login'). Click () driver.find_element_by_link_text ('register now'). Click () # get the handle all_handles=driver.window_handles# of all currently open windows to enter Registration window for handle in all_handles: if handlekeeper searching windows: driver.switch_to.window (handle) print ('now register windows') Driver.find_element_by_name ('userName'). Send_keys (' username') driver.close () time.sleep (2) # return to the search window for handle in all_handles: if handle = = search_windows: driver.switch_to.window (handle) print ('now search window') # close the login pop-up driver.find_element_by_xpath ('/ / * [@ id= "TANGRAM__PSP_2__titleButtons"]') .click () driver.find_element_by_xpath ("/ / input [@ id='kw']") .send_keys ("selenium") driver.find_element_by_id ('su') .click () time.sleep (2) driver.quit ()

The execution process of the above code is as follows: first, open the home page of Baidu, obtain the handle of the current window through current_window_handle, and assign the current handle value to sreach_windows

Open the pop-up box through driver.find_element_by_link_text ('login'). Click ()

Enter the registration page through driver.find_element_by_link_text ('register now'). Click ()

Get all current window handles through driver.window_handles

The first loop, if the current handle is not equal to search_window, then it must not be the home page of Baidu, but must be the registration window. After the registration operation is completed, the registration window is closed through driver.close.

The second cycle, if it is the home page of Baidu, then switch to the home page of Baidu through switch_to.window

Close the login pop-up box via driver.find_element_by_xpath ('/ * [@ id= "TANGRAM__PSP_2__titleButtons"]').

Tags: Handle home page loop search login login switch code file name procedure page learning Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Xiaomi Docker Linux Huawei OPPO Reno