1)确保安装jdk,eclipse,Firefox
2)下载selenium-java-2.41.0.jar和selenium-server-standalone-2.41.0.jar
下载地址是http://docs.seleniumhq.org/download/
selenium-java-2.41.0.jar下载位置如下图
selenium-server-standalone-2.41.0.jar具体下载位置如下
3)打开eclipse新建java工程,将下载的selenium-java-2.41.0.zip解压并粘贴到java工程,将下载的selenium-server-standalone-2.41.0.jar粘贴到java工程。
4)添加JUnit
右击工程名>属性>Java Build Path>Libraries>Add Library 选择JUnit>Next>Finish
5)添加selenium-java-2.41.0.jar和selenium-server-standalone-2.41.0.jar
右击工程名>属性>Java Build Path>Libraries>Add JARs选择刚才粘贴的selenium-java-2.41.0.jar和selenium-server-standalone-2.41.0.jar
6)新建SeleniumTest.java 具体代码如下
import java.io.File;
import junit.framework.Assert;
import org.junit.Before;
import org.junit.After;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxBinary;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class SeleniumTest {
private WebDriver driver=null;
@Before
public void setUp() throws Exception {
System.out.println("setUp");
//如果找不到firefox,使用注视方法
//File pathToFirefoxBinary = new File("F:/Mozilla Firefox/firefox.exe");
//FirefoxBinary firefoxbin = new FirefoxBinary(pathToFirefoxBinary);
//driver=new FirefoxDriver(firefoxbin, null);
driver=new FirefoxDriver();
driver.get("http://www.baidu.com");
}
@After
public void tearDown() throws Exception {
System.out.println("tearDown");
driver.quit();
}
@Test
public void doMyTest(){
WebElement kwElement=driver.findElement(By.id("kw1"));
kwElement.sendKeys("hyddd");
WebElement suElement=driver.findElement(By.id("su1"));
suElement.click();
WebDriverWait wait=new WebDriverWait(driver, 10);
//显示等待。用10s读取元素,如果读取不到将抛出异常,每500ms读取一次。
WebElement element=
wait.until(ExpectedConditions.presenceOfElementLocated(By.id("content_left")));
Assert.assertTrue(element.isDisplayed());
}
}
7)运行Test
右击Test方法>Run as>JUnit test