Home > Article > Backend Development > How do you switch to a new window in Selenium for Python?
Switching to a New Window in Selenium for Python
In Selenium automation using Python, handling multiple browser windows is a common task. When a link is clicked that opens a new window, the focus remains on the original window, preventing actions from being performed in the new one.
To switch the focus from the background window to the newly opened one, you can employ the driver.switch_to.window() method. However, this requires knowing the window's name.
Finding the Window's Name
To retrieve the window's name, you can utilize the window_handles property. It returns a list of currently active window handles. The window handle for the original window can be stored before clicking the link:
window_before = driver.window_handles[0]
After clicking the link, the window handle for the new window can be obtained:
window_after = driver.window_handles[1]
Switching to the New Window
Once you have the window handles, you can switch to the new window using the switch_to.window() method:
driver.switch_to.window(window_after)
Now, the focus is on the new window, allowing you to perform actions such as clicking elements and navigating the page.
Code Example
The following code demonstrates how to switch to a new window in Selenium for Python:
import unittest from selenium import webdriver class GoogleOrgSearch(unittest.TestCase): def setUp(self): self.driver = webdriver.Firefox() def test_google_search_page(self): driver = self.driver driver.get("http://www.cdot.in") window_before = driver.window_handles[0] print(window_before) 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) print(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 do you switch to a new window in Selenium for Python?. For more information, please follow other related articles on the PHP Chinese website!