增加全局的超时 和 等待时间:
import time from selenium.webdriver import Keys, ActionChains from selenium.webdriver.common.by import By from selenium import webdriver from selenium.webdriver.chrome.service import Service from webdriver_manager.chrome import ChromeDriverManager ''' 初始化操作 ''' driver = webdriver.Chrome(service=Service(ChromeDriverManager().install())) def init(): # 最大化操作 driver.maximize_window() driver.set_script_timeout(60) # 智能等待找到元素后立即继续执行,全局生效 driver.implicitly_wait(60) driver.set_page_load_timeout(60) init() ''' 元素点击操作 ''' def clickDemo(): # 点击(鼠标左键)页面按钮:click() driver.get("http://localhost:8080/click.html") button1 = driver.find_element(By.ID, "button1") is_displayed = button1.is_enabled() #判断元素是否是可使用的,True/False if is_displayed: button1.click() # 关闭弹窗 driver.switch_to.alert.accept()
方案二:
在查找元素时,新增一个同名的覆盖方法:
class BasePage(object): log = LoggerClass() def __init__(self, driver, default_timeout=30, sleep=5): self.driver = driver self.default_timeout = default_timeout self.sleep = sleep def find_element(self, by, value, timeout=None, sleep=None): if timeout is None: timeout = self.default_timeout self.log.info("Find the element: ", (by, value)) if sleep is None: time.sleep(self.sleep) else: time.sleep(sleep)
#查看元素:等待,直到找到元素后才返回。如果超过timeout这个超时时间后依然没找到就会抛出异常 element = WebDriverWait(self.driver, timeout=timeout).until(lambda d: d.find_element(by, value)) return element
标签:webdriver,self,driver,selenium4,等待时间,timeout,import,sleep,超时 From: https://www.cnblogs.com/pingguomang/p/17799931.html