• selenium自动化过程中窗口句柄的问题


    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])
    本博客纯粹是学习过程中的笔记,部分来自转载或摘抄,如有侵权,请联系删除 email:18017870857@163.com
  • 相关阅读:
    vue 将毫秒转为日期
    element-ui 点击获取table的行索引
    LInux设置tomcat端口为80
    java引用传递和值传递
    java包装类的自动装箱及缓存
    理解JVM之java内存模型
    理解JVM之类加载机制
    理解JVM之内存分配以及分代思想实现
    理解JVM之垃圾回收
    理解JVM之对象的生命周期
  • 原文地址:https://www.cnblogs.com/yanzhuping/p/14202581.html
Copyright © 2020-2023  润新知