让 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.com/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.com/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.com/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();
}
}
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP