马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要 登录 才可以下载或查看,没有账号?立即注册
×
在Selenium中,等候机制是确保页面元素加载完成后在举行操纵的关键。分别有三种等候机制:显式等候(Explicit Wait)、隐式等候(Implicit Wait)、欺压等候(Force Wait)。
显式等候
显式等候(Explicit Wait)是Selenium提供的一种等候机制,用于在实行操纵之前等候特定条件发生。显式等候可以进步测试的稳固性和可靠性。由于它可以确保元素加载完成或满足特定条件后再举行操纵。在Web主动化测试中,页面加载时间和元素渲染时间大概会有所差别。假如在元素尚未加载完成时实行举行操纵,大概导致测试失败。
长处:
- 机动性高,可以等候特定条件(如元素可点击、文本出现等)
- 进步测试稳固性,只在须要等候时等候,制止不须要的等候时间
缺点:
用法
显式等候通过WebDriver类和expected_conditions模块实现。- # 导入必要模块
- from selenium.webdriver.support.ui import WebDriverWait
- from selenium.webdriver.support import expected_conditions as EC
- from selenium.webdriver.common.by import By
- # 创建WebDriver对象
- wait = WebDriver(driver, 10) # 最多等10秒
- # 使用expected_conditions等待特定条件完成
- element = wait.until(EC.visibility_of_element_located((By.ID, "element_id")))
复制代码 常见的expected_conditions
- element_to_be_clickable:等候元素可点击
- presence_of_element_located:等候元素出如今DOM中
- visibility_of_element_located:等候元素可见
- text_to_be_present_in_element:等候元素中的文本出现
- title_contains:等候页面标题包罗特定文件
- alert_is_present:等候告诫窗出现
等候元素可点击- element = WebDriverWait(driver, 10).until(
- EC.element_to_be_clickable((By.ID, "element_id"))
- )
复制代码 等候元素出如今DOM中- element = WebDriverWait(driver, 10).until(
- EC.presence_of_element_located((By.ID, "element_id"))
- )
复制代码 等候元素可见- element = WebDriverWait(driver, 10).until(
- EC.visibility_of_element_located((By.ID, "element_id"))
- )
复制代码 等候元素中的文本出现- element = WebDriverWait(driver, 10).until(
- EC.text_to_be_present_in_element((By.ID, "element_id"), "expected_text")
- )
复制代码 等候页面标题包罗特定文本- WebDriverWait(driver, 10).until(
- EC.title_contains("expected_title")
- )
复制代码 隐式等候
隐式等候(Implicit Wait)是设置一个全局的等候时间,在查找元素时,假如元素临时不可用,WebDriver将等候一段时间再查找元素。隐式等候的时间是全局的,一旦设置,它将在整个WebDriver实例的生命周期内收效。
长处:
- 简朴易用,只须要设置一次,实用于整个WebDriver实例
- 镌汰代码重复,不须要在每次查找元素时都设置等候时间
缺点:
- 不实用于特定条件,只能等候元素出现,无法等候特定条件(如元素点击、文本出现等)
- 大概导致不须要的等候,假如页面加载速率较快,隐式等候大概会导致不须要的等候时间
用法
- from selenium import webdriver
- driver = webdriver.Chrome()
- driver.implicitly_wait(10) # 设置隐式等待时间为10秒
- driver.get("https://www.example.com")
- # 查找元素,如果元素不可用,WebDriver最多等待10秒
- element = driver.find_element(By.ID, "element_id")
复制代码 欺压等候
欺压等候(Force Wait)是使用time.sleep方法让步调停息实行一段时间。欺压等候是最简朴但也最不保举的等候方式,由于它会无条件地等候指定的时间,大概会导致测试变慢或不稳固。
长处:
缺点:
- 服从低,无条件等候,大概导致测试变慢
- 不稳固,页面加载时间不确定,欺压等候大概导致测试失败或不稳固
用法
- import time
- from selenium import webdirver
- driver = webdriver.Chrome()
- driver.get("https://www.example.com")
- # 强制等待5秒
- time.sleep(5)
- # 查找元素
- element = driver.find_element(By.ID, "element_id")
复制代码 |