如何等待 Selenium 中的元素不再存在?
我们可以在 Selenium webdriver 中等待一个元素不再存在。这可以通过 Selenium 中的同步来实现。我们将添加一个显式等待条件,在那里我们将停止或等待该元素不再存在于页面上。
显式等待时间过去后,如果元素的预期行为仍然不可用,将引发超时异常。要检查一个元素是否不再存在于页面上,我们可以借助预期条件invisibilityOfElementLocated。
要实现显式等待条件,我们必须借助 WebDriverWait 和 ExpectedCondition 类。
示例
代码实现。
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;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class ElementInvisibleWait{
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");
driver.manage().timeouts().implicitlyWait(3, TimeUnit.SECONDS);
// identify element and click()
driver.findElement(By.xpath("//*[text()='Library']")).click();
// explicit wait of invisibility condition
WebDriverWait w = new WebDriverWait(driver,5);
// invisibilityOfElementLocated condition
w.until(ExpectedConditions.
invisibilityOfElementLocated(By.xpath("//*[@class='mui-btn']")));
// get page title of next page
System.out.println("Page title after click:" + driver.getTitle());
driver.close()
}
}输出

广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP