讓 Selenium 等待 10 秒。
我們可以讓 Selenium 等待 10 秒。這可以使用 Thread.sleep 方法來完成。此處,等待時間(10 秒)作為引數傳遞給方法。
我們也可以在 Selenium 中使用 同步 概念進行等待。有兩種等待——隱式 和 顯式。這兩者都是動態的,但隱式等待應用於自動化的每一步,顯式等待只適用於特定元素。
示例
使用睡眠方法的程式碼實現。
import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import java.util.concurrent.TimeUnit; public class WaitThrd{ public static void main(String[] args) throws InterruptedException{ System.setProperty("webdriver.chrome.driver", "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe"); WebDriver driver = new ChromeDriver(); driver.get("https://tutorialspoint.tw/index.htm"); // wait time added Thread.sleep(200); // identify element, WebElement m=driver.findElement(By.id("gsc−i−id1")); m.sendKeys("Java"); driver.close(); } }
示例
使用隱式等待的程式碼實現。
import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import java.util.concurrent.TimeUnit; public class WaitImplicit{ public static void main(String[] args) throws InterruptedException{ System.setProperty("webdriver.chrome.driver", "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe"); WebDriver driver = new ChromeDriver(); // implicit wait driver.manage().timeouts().implicitlyWait(4, TimeUnit.SECONDS); driver.get("https://tutorialspoint.tw/index.htm"); // identify element, WebElement m=driver.findElement(By.id("gsc−i−id1")); m.sendKeys("Python"); driver.close(); } }
示例
使用顯式等待的程式碼實現。
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 WaitExplicit{ public static void main(String[] args) throws InterruptedException{ System.setProperty("webdriver.chrome.driver", "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe"); WebDriver driver = new ChromeDriver(); driver.get("https://tutorialspoint.tw/index.htm"); // identify element, WebElement l=driver.findElement(By.xpath("//*[text()='Library']")); l.click(); //explicit wait WebDriverWait w = new WebDriverWait(driver,7); //expected condition w.until(ExpectedConditions. invisibilityOfElementLocated(By.xpath("//*[@class='mui−btn']"))); driver.close(); } }
廣告