Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Explicit Wait trong Selenium làm gì?


Explicit waits (chờ tường minh) được áp dụng cho một phần tử cụ thể trên trang web. Nó tạm dừng thực thi cho đến khi điều kiện được thỏa mãn. Explicit wait cũng là động vì nếu thời gian chờ là 15 giây và các điều kiện (như chờ phần tử có thể click, hiển thị hoặc chọn được, v.v.) được thỏa mãn trước thời gian chỉ định, điều khiển sẽ chuyển sang bước tiếp theo.

Explicit wait linh hoạt hơn vì chúng ta có thể thiết lập nó cho điều kiện. Danh sách một số expected conditions (điều kiện mong đợi) cho explicit waits được liệt kê dưới đây:

  • textToBePresentInElement()

    Cú pháp

    w.until(ExpectedConditions.textToBePresentInElement(By.id(“<<id expression>>“), “Tutorialspoint”));
  • elementToBeClickable()

    Cú pháp

    w.until(ExpectedConditions.elementToBeClickable(By.id(“<<id expression>>“)));
  • alertIsPresent()

    Cú pháp

    w.until(ExpectedConditions.alertIsPresent())= null);
  • frameToBeAvailableAndSwitchToIt()

    Cú pháp

    w.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.id(“<<frame id >>“)));

Explicit wait phức tạp về mặt triển khai, tuy nhiên nó không ảnh hưởng đến tốc độ thực thi và áp dụng cho một phần tử cụ thể trên trang.

Trong explicit wait, khi thời gian tối đa đã qua, ElementNotVisibleException sẽ được ném ra.

Ví dụ

import org.openqa.selenium.By; import org.openqa.selenium.Keys; 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.Wait; public class Explictwt {    public static void main(String[] args) {       System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");       WebDriver driver = new ChromeDriver();       String url = "https://www.tutorialspoint.com/index.htm";       driver.get(url);       //implicit wait with time in seconds applied to each elements       driver.manage().timeouts().implicitlyWait(12, TimeUnit.SECONDS);       //Clicking on Coding Ground link       driver.findElement(By.xpath("//span[text()=’Coding Ground’]")).click();       // explicit wait declaration       WebDriverWait w = new WebDriverWait(driver,10);       // condition to wait for with textToBePresentInElement method       w.until(ExpectedConditions.textToBePresentInElement(By.xpath("//img[@title=’Whiteboard’]"),”          Whiteboard”));       driver.quit();    } }