How to handle child windows in Selenium with python?

Selenium Web DriverAutomation TestingSoftware Testing

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 −

  • current_window_handle

    This method fetches the handle of the present window.

Syntax

driver.current_window_handle
  • window_handles

    This method fetches all the handle ids of the windows that are currently open.

Syntax

driver.window_handles
w = driver.window_handles[2]

The above code gives the handle id of the second window opened in the present session.

  • switch_to.window(args)

    This method switches the focus of Selenium to the window name mentioned in the arguments.

Syntax

driver.switch_to.window(childwindow)

The above code switches focus to the child window handle.

Example

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[1]
#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()
raja
Published on 29-Jul-2020 12:54:48
Advertisements