Home > Software engineering >  Why is switch_to_window() method not working for selenium webdriver in Python?
Why is switch_to_window() method not working for selenium webdriver in Python?

Time:12-15

I am trying to switch to a newly opened window using the Python selenium webdriver. The code worked fine before but now it is showing error. Surprisingly, the switch_to_window() method is not being recognized by Python and has no declaration to go to.

def process_ebl_statements(self, account_number):

    current_window = self.driver.current_window_handle
    all_windows = self.driver.window_handles

    print("Current window: ", current_window)
    print("All windows: ", all_windows)
    number_of_windows = len(all_windows)
    self.driver.switch_to_window(all_windows[number_of_windows - 1])

Error details:

'WebDriver' object has no attribute 'switch_to_window'

enter image description here

CodePudding user response:

This error message...

'WebDriver' object has no attribute 'switch_to_window'

...implies that the WebDriver object no more supports the attribute switch_to_window()


switch_to_window

switch_to_window was deprecated in Selenium v2.41 :

Selenium 2.41

  • deprecating switch_to_* in favour of driver.switch_to.*

Hence you see the error.


Solution

Instead of switch_to_window you need to use switch_to.

Examples:

  • driver.switch_to.active_element
  • driver.switch_to.alert
  • driver.switch_to.default_content()
  • driver.switch_to.frame()
  • driver.switch_to.parent_frame()
  • driver.switch_to.window('main')
  • Related