如何在Selenium中等待元素出現?
我們可以在Selenium Webdriver中等待元素出現。這可以透過同步機制來實現。我們有一個明確的等待條件,在執行下一步之前,我們可以暫停或等待元素出現。
顯式等待在丟擲異常之前,會等待一段時間。為了驗證是否存在元素,我們可以使用預期條件presenceOfElementLocated.
示例
程式碼實現。
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 ElementPresenceWait{ 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://tutorialspoint.tw/about/about_careers.htm"; driver.get(url); driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS); // identify element and click() WebElement l=driver.findElement(By.linkText("Terms of Use")); l.click(); // explicit wait condition WebDriverWait w = new WebDriverWait(driver,3); // presenceOfElementLocated condition w.until(ExpectedConditions.presenceOfElementLocated (By.cssSelector("h1"))); // get text of element and print System.out.println("Element present having text:" + l.getText()); driver.quit() } }
輸出
廣告