Home > Backend Development > Python Tutorial > How to Switch to a New Window in Selenium for Python?

How to Switch to a New Window in Selenium for Python?

DDD
Release: 2024-11-08 13:00:02
Original
261 people have browsed it

How to Switch to a New Window in Selenium for Python?

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:

  1. Before clicking the link, store the current window handle as window_before.
  2. After clicking the link, store the window handle of the new window as window_after.
  3. Use the switch_to.window() method to move to the new window: driver.switch_to.window(window_after).

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()
Copy after login

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template