1/如果已知接下来的操作会增加新的窗口,可以直接使用如下方法
def switch_to_cur_win(driver):
try:
all_win = driver.window_handle
all_win_num = len(all_win)
driver.switch_to.window(all_win[all_win_num-1])
except Exception as e:
print('切换窗口异常:',e)
2/如果在操作的过程中不知道是否会增加新的窗口,则可以改进一下
def switch_to_cur_win_ifchange(driver, exec_fun=None):
pre_win_num = len(driver.window_handles)
if exec_fun is not None:
exec_fun()
all_win = driver.window_handles
cur_win_num = len(all_win)
if cur_win_num != pre_win_num:
driver.switch_to.window(all_win[cur_win_num - 1])
def get_element(driver, selector, is_immedite=None):
check_loading_is_hide(driver)
wait = WebDriverWait(driver, 10, 0.5)
text = None
# 支持选择器中带文本 比如:div>span[text]=病例 正常选择器中是没有这种写法的
if selector.find("[text]=") > -1:
selector, text = selector.split("[text]=")
if selector.startswith("/") or selector.find("following-sibling::")>-1:
if is_immedite:
elements = driver.find_elements_by_xpath(selector)
else:
elements = wait.until(EC.presence_of_all_elements_located((By.XPATH, selector)))
else:
if is_immedite:
elements = driver.find_elements_by_css_selector(selector)
else:
elements = wait.until(EC.presence_of_all_elements_located((By.CSS_SELECTOR, selector)))
if len(elements) > 0 and text is not None:
for ele in elements:
if ele.text == text:
return ele
return None
return elements[0] if elements is not None and len(elements) > 0 else None
#调用该方法
switch_to_cur_win_ifchange(driver, lambda: get_element(driver, case.get("selector")).click())
3/也可以切换到指定的页面
# 切换到指定窗口 change_num 负数表示前第几个窗口,正数表示后第几个窗口
def switch_to_win(driver, change_num):
all_win = driver.window_handles
cur_win = driver.current_window_handle
index = all_win.index(cur_win)
driver.switch_to.window(all_win[index+change_num])