然后更新一下项目,就会自动下载依赖的第三方jar了,下载完成后,编译通过。下面是完整的代码:
package learn;
import static org.junit.Assert.fail;
import java.util.concurrent.TimeUnit;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.NoAlertPresentException;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class firstScript {
private WebDriver driver;
private String baseUrl;
private boolean acceptNextAlert = true;
private StringBuffer verificationErrors = new StringBuffer();
@Before
public void setUp() throws Exception {
driver = new FirefoxDriver();
baseUrl = "https://www.baidu.com/";
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
@Test
public void test1() throws Exception {
driver.get(baseUrl + "/");
driver.findElement(By.id("kw")).click();
driver.findElement(By.id("kw")).clear();
driver.findElement(By.id("kw")).sendKeys("test");
driver.findElement(By.id("su")).click();
}
@After
public void tearDown() throws Exception {
driver.quit();
String verificationErrorString = verificationErrors.toString();
if (!"".equals(verificationErrorString)) {
fail(verificationErrorString);
}
}
private boolean isElementPresent(By by) {
try {
driver.findElement(by);
return true;
} catch (NoSuchElementException e) {
return false;
}
}
private boolean isAlertPresent() {
try {
driver.switchTo().alert();
return true;
} catch (NoAlertPresentException e) {
return false;
}
}
private String closeAlertAndGetItsText() {
try {
Alert alert = driver.switchTo().alert();
String alertText = alert.getText();
if (acceptNextAlert) {
alert.accept();
} else {
alert.dismiss();
}
return alertText;
} finally {
acceptNextAlert = true;
}
}
}
上面这段脚本是IDE录制下来的,有一些不必要的方法可以删掉,isElementPresent是查看元素是否显示,isAlertPresent是判断页面上是否有alert窗口弹出,closeAlertAndGetItsText是关闭alert窗口,并获取alert的文本信息。处理后的脚本实际上只有下面一段是有用的:
private WebDriver driver;
private String baseUrl;
@Before
public void setUp() throws Exception {
driver = new FirefoxDriver();
baseUrl = "https://www.baidu.com/";
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
@Test
public void test1() throws Exception {
driver.get(baseUrl + "/");
driver.findElement(By.id("kw")).click();
driver.findElement(By.id("kw")).clear();
driver.findElement(By.id("kw")).sendKeys("test");
driver.findElement(By.id("su")).click();
}
@After
public void tearDown() throws Exception {
driver.quit();
}
针对这条脚本,下面逐行解释一下