try except循环3次失败抛异常

需求:

自动化点检定位元素。如果元素不存在,则刷新网页,刷新3次还定位不到元素,则抛异常

 

原来

# 点击操作
def click_btn(by, locator):
    try:
        element = WebDriverWait(driver, 30).until(expected_conditions.element_to_be_clickable((by, locator)))
        element.click()
    except Exception as e:
        raise e

改版后

# 加强版点击操作(定位不到元素自动刷新3次)     
def click_btn(by, locator):
    try:
        for x in range(4):
            try:
                element = WebDriverWait(driver, 30).until(expected_conditions.element_to_be_clickable((by, locator)))
                element.click()
            except Exception as e:
                if x == 3:
                    raise e
                driver.refresh()
            else:
                break            
    except Exception as e:
        raise e

 

posted @ 2021-06-07 15:18  豆浆D  阅读(307)  评论(0编辑  收藏  举报