Skip to content Skip to sidebar Skip to footer

How To Switch Window Handles Using Selenium And Python

If you click a link in a Windows program other than a web browser, a pop-up window appears. I want to get the url of this popup window. Pop-up windows will only open in IE. driver

Solution 1:

As Simon clearly mentioned in a discussion:

While the datatype used for storing the list of handles may be ordered by insertion, the order in which the WebDriver implementation iterates over the window handles to insert them has no requirement to be stable. The ordering is arbitrary.

So you have to:

  • Induce WebDriverWait for number_of_windows_to_be(2)
  • As the order of the windows are random, you can obtain the set of window handles before the interaction is performed and compare it with the set after the action is performed.
  • You can use the following solution:

    driver = webdriver.Ie('C://Users/aaa/IEDriverServer.exe')
    driver.implicitly_wait(3)
    windows_before  = browser.current_window_handle
    pyautogui.moveTo(1576, 660)
    pyautogui.click()
    WebDriverWait(driver, 10).until(EC.number_of_windows_to_be(2))
    windows_after = driver.window_handles
    new_window = [x for x in windows_after if x != windows_before][0]
    driver.switch_to.window(new_window)
    

References: You can find a couple of relevant discussions in:

Solution 2:

I usually use send_keys() instead of click() to handle pop-up window.

Try to use following code:

pyautogui.send_keys(Keys.CONTROL + Keys.ENTER)
driver.find_element_by_tag_name('body').send_keys(Keys.CONTROL + "2")
# window_handles[-1] refer to last window created.
driver.switch_to.window(self.driver.window_handles[-1])
url = driver.current_url
print(url)

Solution 3:

For get current url, you can use :

windows = driver.current_url
print(windows)

Post a Comment for "How To Switch Window Handles Using Selenium And Python"