package javaBase; import org.openqa.selenium.*; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import java.util.concurrent.TimeUnit; /** * java selenium 頁面加載 * 我們經常會碰到用selenium操作頁面上某個元素的時候, 需要等待頁面加載完成后, 才能操作。 否則頁面上的元素不存在,會拋出異常。 * * 或者碰到AJAX異步加載,我們需要等待元素加載完成后, 才能操作 * * selenium 中提供了非常簡單,智能的方法,來判斷元素是否存在. * * 實例:html * 點擊click 按鈕5秒后, 頁面上會出現一個紅色的div快, 我們需要寫一段自動化腳本智能的去判斷這個div是否存在, 然后把這個div 然后高亮。 */ public class TestSetSeleniumServerJAR { public static void main(String[] args) { //谷歌瀏覽器 WebDriver driver = new ChromeDriver(); /** * 隱式等待 */ /* driver.get("http://localhost:8888/Selenium/"); / //總共等待10秒, 如果10秒后,元素還不存在,就會拋出異常 org.openqa.selenium.NoSuchElementException driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS); WebElement element = driver.findElement(By.cssSelector(".red_box")); ((JavascriptExecutor)driver).executeScript("arguments[0].style.border = \"5px solid yellow\"",element); */ /** * 顯式等待 * * 顯式等待 使用ExpectedConditions類中自帶方法, 可以進行顯試等待的判斷。 * * 顯式等待可以自定義等待的條件,用於更加復雜的頁面等待條件 * */ driver.get("http://localhost:8888/Selenium/"); /** *只有滿足顯式等待的條件滿足,測試代碼才會繼續向后執行后續的測試邏輯 * * 如果超過設定的最大顯式等待時間閾值, 這測試程序會拋出異常。 */ WebDriverWait wait = new WebDriverWait(driver, 20); wait.until(ExpectedConditions.presenceOfElementLocated(By.cssSelector(".red_box"))); WebElement element = driver.findElement(By.cssSelector(".red_box")); ((JavascriptExecutor)driver).executeScript("arguments[0].style.border = \"5px solid yellow\"",element); /** * 等待的條件 * * WebDriver方法 * * 頁面元素是否在頁面上可用和可被單擊 * * elementToBeClickable(By locator) * * 頁面元素處於被選中狀態 * * elementToBeSelected(WebElement element) * * 頁面元素在頁面中存在 * * presenceOfElementLocated(By locator) * * 在頁面元素中是否包含特定的文本 * * textToBePresentInElement(By locator) * * 頁面元素值 * * textToBePresentInElementValue(By locator, java.lang.String text) * * 標題 (title) * * titleContains(java.lang.String title) */ } }