1、用WebDriver打开FireFox的一个网址
package com.learningselenium.simplewebdriver;
import org.openqa.selenium.*; //导入Selenium库
import org.openqa.selenium.firefox.FirefoxDriver; //导入FirefoxDriver库
public class testFirefoxDriver
{
public static void main(String[] args)
{
WebDriver driver=new FirefoxDriver(); //启动FirefoxDriver
driver.get("http://www.baidu.com"); //在Firefox中打开百度主页
String url=driver.getCurrentUrl(); //获取当前页面的URL地址,并存储于url中
System.out.println(url); //将地址打印出来
driver.close(); //关闭浏览器
}
}
2、操作系统浏览器最大化---junit结构
package com.learningselenium.normalwebdriver ;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class testMaxmizeBrowser{
WebDriver driver=new FirefoxDriver(); //启动FirefoxDriver
@Before
public void setUp() throws Exception{
driver.get(http://www.baidu.com/);
@Test
public void testMamizeBrower() throws Exception{
driver.manage().window().maxmize(); //浏览器窗口最大化
}
@After
public void tearDown() throws Exception{
driver.quit(); //关闭浏览器
}
}
3、浏览器前进和后退
package com.learningselenium.normalwebdriver;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class testNavigate{
public static void main(String...args){
WebDriver driver=new FirefoxDriver();//启动FirefoxDriver
driver.get("http://www.baidu.com");
system.out.println("Go to url:"+driver.getCurrentUrl);
driver.navigate().to("http://www.cnblogs.com"); //打开测试页面,P.S.navigate方法会产生1个Navigator对象,其封装了与导航相关的一些方法,比如前进后退等
system.out.println("Navigate to url:"+driver.getCurrentUrl());
driver.navigate().refresh();
driver.navigate().back();
system.out.println("Back to url:"+driver.getCurrentUrl());
driver.navigate().forward();
system.out.println("Forward to url:"+driver.getCurrentUrl());
driver.quit();
}
}
4、页面元素定位
Webdriver提供下面两种方法来定位页面元素,参数是By对像,最常用是By.id和By.name查找。
- findElement 定位某个元素,如果没有找到元素会抛出异常:NoSuchElementException
- findElements 定位一组元素
例如需要定位如下元素:
<input class="input_class" type="text" name="passwd" id="passwd-id" />
- By.id:
WebElement element = driver.findElement(By.id("passwd-id"));
- By.name:
WebElement element = driver.findElement(By.name("passwd"));
- By.xpath:
WebElement element =driver.findElement(By.xpath("//input[@id='passwd-id']"));
- By.className
WebElement element = driver.findElement(By.className("input_class"));
- By.cssSelector
WebElement element = driver.findElement(By.cssSelector(".input_class"));
- By.linkText:
//通俗点就是精确查询
WebDriver driver = new FirefoxDriver();
driver.get("http://www.baidu.com/");
WebElement element = driver.findElement(By.linkText("百科"));
- By.partialLinkText:
//这个方法就是模糊查询
WebDriver driver = new FirefoxDriver();
driver.get("http://www.baidu.com/");
WebElement element = driver.findElement(By.partialLinkText("hao"));
- By.tagName:
WebDriver driver = new FirefoxDriver();
driver.get("http://www.baidu.com/");
String test= driver.findElement(By.tagName("form")).getAttribute("name");
System.out.println(test);
5、对页面元素进行操作
5.1输入框(text field or textarea)
WebElement element = driver.findElement(By.id("passwd-id"));
- element.sendKeys(“test”); //在输入框中输入内容:
- element.clear(); //将输入框清空
- element.getText(); //获取输入框的文本内容
5.2下拉选择框(Select)
Select select = new Select(driver.findElement(By.id("select")));
- select.selectByVisibleText(“A”);
- select.selectByValue(“1”);
- select.deselectAll();
- select.deselectByValue(“1”);
- select.deselectByVisibleText(“A”);
- select.getAllSelectedOptions();
- select.getFirstSelectedOption();
5.3单选项Radio Button
package com.learningselenium.normalwebdriver;
import static org.junit.Assert.*;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.WebElement;
public class testRadioButton{
//WebDriver driver=new FierfoxDriver();
WebDriver driver=new FirefoxDriver(); //启动FirefoxDriver
@Before
public void setUp() throws Exception{
driver.get("file:///F:/2015%E5%B9%B49%E6%9C%8830/qhr.html");
}
@Test
public void dd() throws Exception{
WebElement femaleRadioButton= driver.findElement(By.xpath("/html/body/form/input[2]"));
if(!femaleRadioButton.isSelected()){ //判断某个单选项是否已经被选择
femaleRadioButton.click(); //选择某个单选项
}
assertTrue(femaleRadioButton.isSelected());
}
@After
public void tearDown()throws Exception{
driver.quit();
}
}
- radio.clear(); //清空某个单选项
5.4多选项checkbox
package com.learningselenium.normalwebdriver;
import static org.junit.Assert.assertTrue;import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.WebElement;public class testCheckbox {
WebDriver driver=new FirefoxDriver();@Before
public void setUp() throws Exception{
driver.get("file:///F:/2015%E5%B9%B49%E6%9C%8830/%E5%A4%9A%E9%80%89%E6%8C%89%E9%92%AE.html");
}
@Test
public void testCheckbox() throws Exception{
WebElement bikeCheckbox=
driver.findElement(
By.xpath("/html/body/form/input[1]"));
if(!bikeCheckbox.isSelected()){
bikeCheckbox.click();
}
assertTrue(bikeCheckbox.isSelected());
WebElement carCheckbox=
driver.findElement(
By.cssSelector("input[value='car']"));
if(!carCheckbox.isSelected()){
carCheckbox.click();
}
assertTrue(carCheckbox.isSelected());
}
@After
public void tearDown()throws Exception{
driver.quit();
}
}- checkbox.click();
- checkbox.clear();
- checkbox.isSelected();
- checkbox.isEnabled();
5.5按钮button
WebElement btn= driver.findElement(By.id("save"));
- btn.click(); //点击按钮
- btn.isEnabled (); //判断按钮是否enable
5.6弹出框
package com.learningselenium.normalwebdriver;
import static org.junit.Assert.assertTrue;import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.Alert;public class testDialogs {
WebDriver driver=new FirefoxDriver();
@Before
public void setUp() throws Exception{
driver.get("file:///F:/2015%E5%B9%B49%E6%9C%8830/%E5%A4%9A%E9%80%89%E6%8C%89%E9%92%AE.html");
}
@Test
public void testAlertDialog() throws Exception{ //警告框
WebElement alertButton=
driver.findElement(
By.xpath("/html/body/form/input[1]"));
alertButton.click();
Alert javascriptAlert=driver.switchTo().alert();
system.out.println(javascriptAlert.getText());
javascriptAlert.accept();
}
@Test
public void testPromptDialog() throws Exception{ //提示框
WebElement promptButton=
driver.findElement(
By.xpath("/html/body/form/input[1]"));
promptButton.click();
Alert javascriptPrompt=driver.switchTo().alert();
javascriptPrompt.sendkeys("This is Learning selenium");
javascriptPrompt.accept();
system.out.println(javascriptPrompt.getText());
javascriptPrompt=driver.switchTo().alert();
javascriptPrompt.accept();
promptButton.click();
javascriptPrompt=driver.switchTo().alert();
system.out.println(javascriptPrompt.getText());
javascriptPrompt.dismiss();
javascriptPrompt=driver.switchTo().alert();
system.out.println(javascriptPrompt.getText());
javascriptPrompt.accept();
}
@Test
public void testConfirmDialog() throws Exception{ //确认框
WebElement confirmButton=
driver.findElement(By.xpath("/html/body/form/input[1]"));
confirmButton.click();
Alert javascriptConfirm=driver.switchTo().alert();
javascriptConfirm.accept();
javascriptConfirm=driver.switchTo().alert();
system.out.println(javascriptConfirm.getText());
javascriptConfirm.accept();
ConfirmButton.click();
javascriptConfirm=driver.switchTo().alert();
system.out.println(javascriptConfirm.getText());
javascriptConfirm.dismiss();
javascriptConfirm=driver.switchTo().alert();
system.out.println(javascriptConfirm.getText());
javascriptConfirm.accept();
}
@After
public void tearDown() throws Exception{
driver.quit();
}
}
Alert alert = driver.switchTo().alert();
- alert.accept(); //确定
- alert.dismiss(); //取消
- alert.getText(); //获取文本
5.7等待时间设置
package com.learningselenium.normalwebdriver;
import java.util.concurrent.TimeUnit;import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.openqa.selenium.support.ui.ExpectedCondition;public class testWait {
public static void main(String...args){
WebDriver driver=new FirefoxDriver();
driver.get("http://www.google.com");
WebElement SearchBox=driver.findElement(By.name("q"));
searchBox.sendkeys("Selenium2");
searchBox.submit();
//Explicit wait
(new WebDriverWait(driver,10)).
until(new ExoectedCondition<Boolean>()){
public Boolean apply(WebDriver d){
return d.getTitle().toLowerCase().startsWith("Selenium");
}
});
system.out.println("Page title is:"+driver.getTitle());
driver.navigate().back();
//implicit wait
driver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS);
driver.findElement(By.name("btnk")).click();
driver.quit();
}
}WebDriver driver = new FirefoxDriver();
- driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); //识别元素时的超时时间
- driver.manage().timeouts().pageLoadTimeout(10, TimeUnit.SECONDS); //页面加载时的超时时间
- driver.manage().timeouts().setScriptTimeout(10, TimeUnit.SECONDS); //异步脚本的超时时间
5.8弹出窗口的验证标题
package com.learningselenium.normalwebdriver;
import static org.junit.Assert.*;
import java.util.Set;
import java.junit.After;
import java.junit.Before;
import java.junit.Test;import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;public class testMultipleWindowsTitle {
WebDriver driver=new FirefoxDriver();@Before
public void setup()throws Exception{
driver.get("http://www.w3schools.com/jsref/met_win_open.asp");
}
@Test
public void testMultipleWindowsTitle()throws Exception{
String parentWindowld=driver.getWindowHandle();
assertEquals("Window open()Method",driver.getTitle());
WebElement tryltButton=driver.findElement(By.xpath("//*[@id=\"main\"]/div[2]/a"));
tryltButton.click();
Set<String>allWindowsld=driver.getWindowHandles();
for(String windowld:allWindowld){
if(driver.switchTo().window(window).getTitle().contains("Tryit")){
driver.switchTo().window(windowld);
break;
}
}
assertEquals("Tryit Editor v1.8",driver.getTitle());
}
@after
public void tearDown()throws Exception{
driver.quit();
}
}5.9弹出窗口的验证内容
package com.learningselenium.normalwebdriver;
import static org.junit.Assert.assertEquals;
import java.util.Set;
import java.junit.After;
import java.junit.Before;
import java.junit.Test;import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;public class testMultiplePageContain {
WebDriver driver=new FirefoxDriver();@Before
public void setup()throws Exception{
driver.get("http://www.w3schools.com/jsref/met_win_open.asp");
}
@Test
public void testMultiplePageContain()throws Exception{
String parentWindowld=driver.getWindowHandle();
assertEquals("Window open()Method",driver.getTitle());
WebElement tryltButton=driver.findElement(By.xpath("//*[@id=\"main\"]/div[2]/a"));
tryltButton.click();
Set<String>allWindowsld=driver.getWindowHandles();
for(String windowld:allWindowld){
if(driver.switchTo().window(window).getPageSource().contains("Open a new brower window")){
driver.switchTo().window(windowld);
break;
}
}
assertEquals("Tryit Editor v1.8",driver.getTitle());
driver.switchTo().window(parentWindowld);
assertEquals("Window open()Method",driver.getTitle());
}
@After
public void tearDown()throws Exception{
driver.quit();
}
}
5.10浏览器的Cookies -
-
package com.learningselenium.normalwebdriver;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter; -
import org.openqa.selenium.By;
import org.openqa.selenium.Cookies;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver; -
public class testGetCookies {
public static void main(String...args){
WebDriver driver=new FirefoxDriver();
driver.get("http://www.zhihu.com/#signin");
driver.findElement(By.name("email")).sendkeys("seleniumcookies@126.com");
driver.findElement(By.name("password")).sendkeys("cookies123");
if(driver.findElement(By.name("remember")).isSelected()){
driver.findElement(By.name("remember")).click();
}
driver.findElement(By.className("sign-button")).click();
File cookiesFile=new File("zhihu.cookies.txt");
try{
cookieFile.delete();
cookieFile.createNewFile();
FileWriter fileWriter=new BufferedWriter=new BufferedWriter(fileWriter);
for(Cookie cookie:driver.manage().getCookies()){
bufferWriter.write((cookie.getName()+";"
+cookie.getValue()+";"
+cookie.getDomain()+";"
+cookie.getPath()+";"
+cookie.getExpiry()+";"
+cookie.isSecure()));
bufferWriter.newLine();
}
bufferWriter.flush();
bufferWriter.close();
file.Writer.close();
}catch(Exception ex){
ex.printStackTrace();
}
driver.quit();
}
}//从文件了读取保存的Cookies信息,并自动填充信息
-
package com.learningselenium.normalwebdriver;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.Date;
import java.util.StringTokenizer;import org.openqa.selenium.Cookie;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;public class testAddCookies {
private static BufferedReader bufferedReader;
public static void main(String...args){
WebDriver driver=new FirefoxDriver();
driver.get("http://www.zhihu.com/#signin");
try{
File cookieFile=new File("zhihu.cookies.txt");
FileReader fr=new FileReader(cookieFile);
bufferedReader=new BufferedReader(fr);
String line;
while((line=bufferedReader.readerLine())!=null){
StringTokenizer stringTokenizer=new StringTokenizer(line,";");
while(stringTokenizer.hasMoreTokens()){
String name=stringTokenizer.nextToken();
String value=stringTokenizer.nextToken();
String domain=stringTokenizer.nextToken();
String path=stringTokenizer.nextToken();
Date expiry=null;
String dt;
if(!(dt=stringTokenizer.nextToken()).equals("null")){
expiry=new Date(dt);
}
boolean isSecure=new Boolean(stringTokenizer.nextToken()).booleanValue();
Cookie cookie=new Cookie(name,value,domain,path,expiry,isSecure);
driver.manage().addCookie(cookie);
}
}
}catch(Exception ex){
ex,printStackTrace();
}
driver.get("http://www.zhihu.com");
}
}