We can handle child windows or tabs in Selenium. While working with child windows, we need to always shift the browser focus to the child windows, then perform operation on them.
By default, the focus remains on the first parent window. There are multiple methods available in Selenium which are listed below −
This method fetches the handle of the present window.
This method fetches all the handle ids of the windows that are currently open.
driver.window_handles w = driver.window_handles
The above code gives the handle id of the second window opened in the present session.
This method switches the focus of Selenium to the window name mentioned in the arguments.
The above code switches focus to the child window handle.
Code Implementation with child window.
from selenium import webdriver driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe") # to maximize the browser window driver.maximize_window() #get method to launch the URL driver.get("https://the-internet.herokuapp.com/windows") #to refresh the browser driver.refresh() driver.find_element_by_link_text("Click Here").click() #prints the window handle in focus print(driver.current_window_handle) #to fetch the first child window handle chwnd = driver.window_handles #to switch focus the first child window handle driver.switch_to.window(chwnd) print(driver.find_element_by_tag_name("h3").text) #to close the browser driver.quit()