在使用selenium做web自动化的过程中,可能会因为网络等原因导致页面元素没用加载出来就执行了代码,进而导致报错。接下来介绍三种等待的方式:
1. 强制等待
通过sleep来实现强制等待,但是时间点不好控制,如果等待的时间不够,那么还是定位不到元素,如果设置等待的时间过长,元素已经可以定位到,程序还在等待,太浪费时间
2. 隐性等待
implicitly_wait相对sleep来说是一种比较智能的等待方式,设置完超时时间后,在时间内找到就直接返回元素,未找到元素则超时报错。
需要注意implicitly_wait设置完后整个程序都会有效,是全局的。但是必须等待页面所有的元素加载完成;比如设置10秒,但是在3秒的时候需要的元素已经加载出现,而加载整个页面需要5秒,这样就会影响代码的执行效率。
3. 显性等待
相比前面两种来说是最智能的等待方式,不是全局的每次等待都需要单独设置,只有在时间加载到需要定位的元素,就会继续执行代码。
在自动化测试中推荐使用第3种方式,下面是第3种方式的代码实现
python实现
from selenium.webdriver.support.wait import WebDriverWaitfrom selenium.webdriver.common.by import Byfrom selenium.webdriver.support import expected_conditions as ECclass WaitElement: WAIT_TIME = 10 @classmethod def by_class_name(cls, driver, locator): e = WebDriverWait(driver, cls.WAIT_TIME).until(EC.presence_of_element_located((By.CLASS_NAME, locator))) return e @classmethod def by_id(cls, driver, locator): e = WebDriverWait(driver, cls.WAIT_TIME).until(EC.presence_of_element_located((By.ID, locator))) return e @classmethod def by_xpath(cls, driver, locator): e = WebDriverWait(driver, cls.WAIT_TIME).until(EC.presence_of_element_located((By.XPATH, locator))) return e
java实现
import org.openqa.selenium.By;import org.openqa.selenium.WebDriver;import org.openqa.selenium.WebElement;import org.openqa.selenium.support.ui.ExpectedConditions;import org.openqa.selenium.support.ui.WebDriverWait;public class TestD { public static void main(String[] args) { WebDriver driver = DriverDataSource.getDriver(); waitElement(driver, "elementXpath"); } public static WebElement waitElement(WebDriver driver, String locator){ WebDriverWait wait = new WebDriverWait(driver, 5); return wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath(locator))); }}
留言与评论(共有 0 条评论) “” |