Home >Backend Development >Python Tutorial >How to Switch Between Multiple Browser Windows Using Selenium in Python?
How to Manage Multiple Browser Windows Using Selenium in Python
In the vast realm of web automation, it is often necessary to interact with multiple browser windows or tabs. Selenium, an industry-leading automation framework, empowers Python developers with the ability to navigate these challenges seamlessly.
One common scenario encountered during web testing is the opening of a new browser window upon clicking a link. To effectively perform actions within the newly opened window, we must switch the focus away from the background window.
Finding the Target Window's Handle
Before switching to the new window, we need to identify its handle. This unique identifier represents the specific window instance. To retrieve the handles, we utilize the driver.window_handles method, which returns a list of all open window handles. The handle of the currently focused window will be the first element in this list.
Switching to the New Window
Now that we have the handle of the target window, we can switch to it using the driver.switch_to.window(handle) method. Passing in the target handle effectively moves the focus to the corresponding window, allowing us to perform actions within its context.
Code Example
The following Python code illustrates how to switch to a newly opened 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()
In this example, we are accessing the "http://www.cdot.in" website and clicking a link to open a new window. We then retrieve the handles of the two windows and switch to the newly opened one to perform further actions.
The above is the detailed content of How to Switch Between Multiple Browser Windows Using Selenium in Python?. For more information, please follow other related articles on the PHP Chinese website!