Home > Article > Backend Development > How to Switch Between Multiple Browser Windows in Selenium with Python?
How to Handle Multiple Browser Windows in Selenium with Python
When working with Selenium automation, you may encounter situations where multiple browser windows appear. As the focus remains on the first opened window, navigating or performing actions in subsequent windows becomes challenging. To address this, a key method is the driver.switch_to.window().
Locating the Window Name
Contrary to the notion that driver.switch_to.window() requires a window name, it works on window handles instead. Determining the window handle can be achieved using the window_handles property.
How to Switch to New Window
To switch focus to the newly opened window, follow these steps:
window_before = driver.window_handles[0]
window_after = driver.window_handles[1]
driver.switch_to.window(window_after)
Example
Consider the following code that navigates between multiple windows:
import unittest from selenium import webdriver class WindowHandling(unittest.TestCase): def setUp(self): self.driver = webdriver.Firefox() def test_window_switch(self): driver = self.driver driver.get("http://www.cdot.in") window_before = driver.window_handles[0] driver.find_element_by_xpath("//a[@href='http://www.cdot.in/home.htm']").click() window_after = driver.window_handles[1] driver.switch_to.window(window_after) driver.find_element_by_link_text("ATM").click() driver.switch_to.window(window_before) def tearDown(self): self.driver.close() if __name__ == "__main__": unittest.main()
The above is the detailed content of How to Switch Between Multiple Browser Windows in Selenium with Python?. For more information, please follow other related articles on the PHP Chinese website!