在 Selenium WebDriver 中檢查元素是否可點選
我們可以使用同步檢查元素在 Selenium webdriver 中是否可點選。在同步中,有一個顯式等待,其中驅動程式會等待元素的預期條件滿足。
要驗證元素是否可點選,我們應使用 elementToBeClickable 條件。如果在驅動程式等待時間內元素的標準不滿足,則會丟擲一個超時異常。
語法
WebDriverWait wt = new WebDriverWait(driver, 5); wt.until(ExpectedConditions.elementToBeClickable (By.className("s-buy")));
我們必須新增 - import org.openqa.selenium.support.ui.ExpectedConditions 和 import org.openqa.selenium.support.ui.WebDriverWait 語句,以便在我們的程式碼中實現 ExpectedConditions。
示例
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 ElemntClickable{ public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe"); WebDriver driver = new ChromeDriver(); //implicit wait driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS); //URL launch driver.get("https://tutorialspoint.tw/index.htm"); WebElement n=driver.findElement(By.className("mui-btn")); n.click(); // explicit wait WebDriverWait wt = new WebDriverWait(driver,6); // elementToBeClickable expected criteria wt.until(ExpectedConditions.elementToBeClickable (By.className("s-buy"))); System.out.println("Current page title:" + driver.getTitle()); driver.close(); } }
輸出
廣告