Selenium WebDriver 中等待变化的最佳实践?
在 Selenium 中等待变化的最佳实践是使用**同步**的概念。可以使用**隐式**和**显式**等待来处理等待。隐式等待是应用于页面上每个元素的全局等待。
隐式等待的默认值为 0。它也是动态等待,这意味着如果隐式等待为 5 秒,而元素在第 3 秒可用,则立即执行下一步,无需等待完整的 5 秒。如果 5 秒后元素仍未找到,则会抛出超时错误。
语法
driver.manage().timeouts().implicitlyWait();
示例
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
public class ImpctWt {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver",
"C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://tutorialspoint.com/index.htm");
// wait of 5 seconds
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
// findElement() will try to identify element till 5 secs
WebElement n=driver.findElement(By.id("gsc−i−id1"));
n.sendKeys("Java");
}
}显式等待也用于页面上的特定元素。它是一个与 Expected Condition 类一起工作的 WebDriverWait。它也是动态等待,这意味着如果显式等待为 5 秒,而元素在第 3 秒可用,则立即执行下一步。如果 5 秒后元素仍未找到,则会抛出超时错误。
显式等待的一些预期条件如下:
titleContains(String s)
alertIsPresent()
invisibilityOfElementLocated(By locator)
invisibilityOfElementWithText(By locator, String s)
textToBePresentInElement(By locator, String t)
visibilityOfElementLocated(By locator)
presenceOfAllElementsLocatedBy(By locator)
visibilityOf(WebElement e)
presenceOfElementLocated(By locator)
elementToBeClickable(By locator)
stalenessOf(WebElement e)
示例
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class ExpltWt {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver",
"C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://tutorialspoint.com/index.htm");
// identify element and click()
driver.findElement(By.xpath("//*[text()='Library']")).click();
// expected condition − invisibility condition
WebDriverWait wt = new WebDriverWait(driver,5);
// invisibilityOfElementLocated condition
wt.until(ExpectedConditions.
invisibilityOfElementLocated(By.xpath("//*[@class='mui−btn']")));
driver.close();
}
}
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP