Switching to New Windows in Selenium for Python
In Selenium for Python, handling multiple browser windows can pose a challenge. When a new window opens after clicking a link, the focus remains on the original window, preventing actions from being performed in the new window. To address this issue, you need to switch the driver's focus to the new window.
Determining the Window's Name
The driver.switch_to.window() method requires the window's name. However, Selenium doesn't provide a direct way to obtain this name. Instead, you can use the window_handles attribute to get a list of window handles, which are unique identifiers.
Switching Focus to the New Window
Here are the steps on how to switch focus to the new window:
Example Code
The following Python code illustrates how to handle multiple browser windows and switch focus to the new window:
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 to Switch to a New Window in Selenium for Python?. For more information, please follow other related articles on the PHP Chinese website!