Home  >  Article  >  Backend Development  >  How to Switch Between Multiple Browser Windows in Selenium with Python?

How to Switch Between Multiple Browser Windows in Selenium with Python?

Susan Sarandon
Susan SarandonOriginal
2024-11-08 00:53:02444browse

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:

  1. Before clicking the link that triggers the new window, record the current window handle using:
window_before = driver.window_handles[0]
  1. After clicking the link, retrieve the handle of the new window:
window_after = driver.window_handles[1]
  1. Utilize the switch_to.window(window_handle) method to direct the focus:
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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn