使用 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://www.tutorialspoint.com/index.htm");
// 等待 5 秒
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
// findElement() 将在 5 秒内尝试识别元素
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://www.tutorialspoint.com/index.htm");
// 识别元素并单击()
driver.findElement(By.xpath("//*[text()='Library']")).click();
// 预期条件减去不可见条件
WebDriverWait wt = new WebDriverWait(driver,5);
// invisibilityOfElementLocated 条件
wt.until(ExpectedConditions.
invisibilityOfElementLocated(By.xpath("//*[@class='mui−btn']")));
driver.close();
}
}

