正在尝试确保正确的窗口现在处于活动状态



我试图断言当前所需的浏览器窗口是通过selenium打开的。我的方法是将窗口的标题相互比较,如果标题不匹配,则切换到下一个窗口并重复此过程。但现在没有检查最后一个窗口(这是正确的(。

收集所有打开的浏览器窗口的方法:

def collect_windows(self):
windows = []
try:
for handle in self.driver.window_handles:
windows.append(handle)
return windows
except:
self.log.error(format_exc())

运行列表并检查窗口标题的方法:

def switch_window(self, window_title=''):
windows_list = self.collect_windows()
try:
for window in windows_list:
title = self.driver.title
if window_title not in title:
self.driver.switch_to.window(window)
self.log.info(f"Switched to window: {window_title}")
except:
self.log.error(format_exc())

窗口处理而不是比较标题

def get_current_window_handle(self):
return self.driver.current_window_handle
def switch_window(self, current_handle):
for handle in self.driver.window_handles:
if handle != current_handle:
self.driver.switch_to.window(handle)
self.log.info(f"Switched to window: {self.driver.title}")
return

current_window_handle = get_current_window_handle()
# open new window
switch_window(current_window_handle)

最新更新