为什么 switch_to_window() 方法不适用于 Python 中的 selenium webdriver?

Why is switch_to_window() method not working for selenium webdriver in Python?

我正在尝试使用 Python selenium webdriver 切换到新打开的 window。该代码之前运行良好,但现在显示错误。令人惊讶的是,switch_to_window() 方法未被 Python 识别,并且没有可转到的声明。

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])

错误详情:

'WebDriver' object has no attribute 'switch_to_window'

这个错误信息...

'WebDriver' object has no attribute 'switch_to_window'

...意味着 对象不再支持属性 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.*

因此您会看到错误。


解决方案

而不是 switch_to_window 你需要使用 switch_to.

示例:

  • 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')