11- Use of Selenium element disposed in the java language commonly used API to wait

WebDriver provides two types of wait: the explicit and implicit waiting waiting.

1. Display wait

WebDriver provide an explicit wait method, specifically to wait for the judgment of an element.

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.WebDriverWait;
import org.openqa.selenium.support.ui.ExpectedCondition;
 
 
public class TimeOut01 {
 
  public static void main(String[]args) throws InterruptedException {
 
    WebDriver driver = new ChromeDriver();
    driver.get("https://www.baidu.com");
 
    //显式等待, 针对某个元素等待
    WebDriverWait wait = new WebDriverWait(driver,10,1);
 
    wait.until(new ExpectedCondition<WebElement>(){
      @Override
      public WebElement apply(WebDriver text) {
            return text.findElement(By.id("kw"));
          }
    }).sendKeys("selenium");
 
    driver.findElement(By.id("su")).click();
    Thread.sleep(2000);
 
    driver.quit();
  }
}

WebDriverWait class waiting methods provided by WebDirver. Within the set time, the default time to time be tested once the current page element exists, and if it exceeds the set time does not detect an exception is thrown. The following format: WebDriverWait (driver, 10, 1) driver: browser driver. 10: longest timeout, default in seconds. 1: detection interval (step). The default is 0.5s.

2. Implicit wait

WebDriver provides several ways to wait elements.

  • implicitlyWait. Timeout when identifying objects. After this time, then if the object is not found NoSuchElement will throw an exception.
  • setScriptTimeout. Timeout asynchronous script. WebDriver asynchronously execute script, this script is set to perform asynchronous script returns the result of the timeout.
  • pageLoadTimeout. Page timeout when loading. Because WebDriver will wait for page load before proceeding back, so if the page exceeds the set time is still not loaded, then WebDriver will throw an exception.
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.By;
import java.util.concurrent.TimeUnit;
 
public class TimeOut02 {
 
  public static void main(String[] args){
 
    WebDriver driver = new ChromeDriver();
 
    //页面加载超时时间设置为 5s
    driver.manage().timeouts().pageLoadTimeout(5, TimeUnit.SECONDS);
    driver.get("https://www.baidu.com/");
 
    //定位对象时给 10s 的时间, 如果 10s 内还定位不到则抛出异常
    driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
    driver.findElement(By.id("kw")).sendKeys("selenium");
 
    //异步脚本的超时时间设置成 3s
    driver.manage().timeouts().setScriptTimeout(3, TimeUnit.SECONDS);
 
    driver.quit();
  }
}

Guess you like

Origin www.cnblogs.com/zhizhao/p/11303296.html