1 package com.test.location;2
3 import static org.junit.Assert.*;4
5 import java.util.Iterator;6 import java.util.List;7
8 import javax.lang.model.element.Element;9
10 import org.junit.After;11 import org.junit.Before;12 import org.junit.Test;13 import org.openqa.selenium.By;14 import org.openqa.selenium.WebDriver;15 import org.openqa.selenium.WebElement;16 import org.openqa.selenium.firefox.FirefoxDriver;17
18 public classTestLocation {19 WebDriver driver;20
21 @Before22 public voidsetUp() throws Exception {23
24 driver = newFirefoxDriver();25 driver.get("http://www.baidu.com/");26 //将屏幕最大化
27 driver.manage().window().maximize();28 }29
30 @After31 public voidtearDown() throws Exception {32 //退出浏览器
33 driver.quit();34 }35
36 @Test37 public voidtest001_GetByID() {38 //清空输入框,并输入查询关键字“selenium”,然后点击查询按钮
39 driver.findElement(By.id("kw")).clear();40 driver.findElement(By.id("kw")).sendKeys("selenium");41 driver.findElement(By.id("su")).click();42
43 Boolean flag = driver.findElement(By.linkText("Selenium - Web Browser Automation")).isDisplayed();44 assertTrue("\"Selenium - Web Browser Automation\" is not display",flag);45 }46
47 @Test48 public voidtest002_GetByName(){49 //清空输入框,并输入查询关键字“selenium”,然后点击查询按钮
50 driver.findElement(By.name("wd")).clear();51 driver.findElement(By.name("wd")).sendKeys("selenium");52 driver.findElement(By.id("su")).click();53
54 Boolean flag = driver.findElement(By.linkText("Selenium - Web Browser Automation")).isDisplayed();55 assertTrue("\"Selenium - Web Browser Automation\" is not display",flag);56 }57
58 @Test59 public voidtest003_GetByClass(){60 //清空输入框,并输入查询关键字“selenium”,然后点击查询按钮
61 driver.findElement(By.className("s_ipt")).clear();62 driver.findElement(By.className("s_ipt")).sendKeys("selenium");63 driver.findElement(By.className("bg s_btn")).click();64
65 Boolean flag = driver.findElement(By.linkText("Selenium - Web Browser Automation")).isDisplayed();66 assertTrue("\"Selenium - Web Browser Automation\" is not display",flag);67 }68
69 @Test70 public voidtest004_GetByTag(){71 //清空输入框,并输入查询关键字“selenium”,然后点击查询按钮72 //input 这个tag在百度首页中比较多,所以需要使用findElements(),将所有input返回,并从中找寻需要的两个input
73 List inputs = driver.findElements(By.tagName("input"));74 Iterator it =inputs.iterator();75 WebElement we = null;76 WebElement inputWe = null;77 WebElement buttonWe = null;78 while(it.hasNext()){79 we =(WebElement)it.next();80 if(we.getAttribute("id").toString().equals("kw")){81 inputWe =we;82 }83
84 if(we.getAttribute("id").toString().equals("su")){85 buttonWe =we;86 }87 }88
89 //找到之后开始操作
90 if(inputWe!=null && buttonWe!=null){91 inputWe.clear();92 inputWe.sendKeys("selenium");93 buttonWe.click();94 }else{95 System.out.println("can not find input and button");96 }97
98 //判断结果
99 Boolean flag = driver.findElement(By.linkText("Selenium - Web Browser Automation")).isDisplayed();100 assertTrue("\"Selenium - Web Browser Automation\" is not display",flag);101
102
103
104 }105 }