Explicit waits ใช้กับองค์ประกอบเฉพาะในหน้าเว็บ จะหยุดการรันจนกว่าเงื่อนไขจะเป็นจริง Explicit wait เป็นแบบไดนามิกเช่นกัน เพราะถ้าเวลารอ 15 วินาที และเงื่อนไข (เช่นรอให้ element clickable, visible, selectable ฯลฯ) ถูกต้องก่อนเวลาที่กำหนด การควบคุมจะไปขั้นตอนถัดไป
Explicit wait ปรับแต่งได้มากกว่า เนื่องจากเราสามารถตั้งค่าเงื่อนไขได้ รายการเงื่อนไขที่คาดหวังสำหรับ explicit waits มีดังนี้ -
textToBePresentInElement()
Syntax
w.until(ExpectedConditions.textToBePresentInElement(By.id("<<id expression>>"), "Tutorialspoint"));textToBeClickable()
Syntax
w.until(ExpectedConditions.textToBeClickable(By.id("<<id expression>>")));alertisPresent()
Syntax
w.until(ExpectedConditions.alertisPresent())= null);
frameToBeAvailableAndSwitchToIt()
Syntax
w.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.id("<<frame id >>")));
Explicit wait ซับซ้อนในการนำไปใช้ แต่ไม่ส่งผลต่อความเร็วการรัน และใช้กับองค์ประกอบเฉพาะในหน้า
ใน explicit wait เมื่อเวลาสูงสุดผ่านไป ElementNotVisibleException จะถูกโยน
ตัวอย่าง
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(); } }