高级控件
取多个对象
findElements()方法可以返回一个符合条件的元素List组,例如:
List<WebElement> elements = driver.findElements(By.tagName("input"));
层级定位
不方便定位某元素时,可以先定位其父元素,再取父元素的子元素:
WebElement element = driver.findElements(By.className("login")); List<WebElement> elements = element.findElements(By.tagName("label"));
iframe
网页:
<html> <head> <title>FrameTest</title> </head> <body style="background-color: #990000;"> <div id="id1">this is a div!</div> <iframe id="frame" frameborder="0" scrolling="no" style="left:0;position:absolute;" src="frame.html"></iframe> </body> </html>
frame.html:
<html> <head> <title>this is a frame!</title> </head> <body style="background-color: #009900;"> <div id = "div1">this is a div,too!</div> <label>input:</label> <input id = "input1"></input> </body> </html>
代码:
//在default content定位id="id1"的div dr.findElement(By.id("id1")); //此时,没有进入到id="frame"的frame中时,以下两句会报错 dr.findElement(By.id("div1"));//报错 dr.findElement(By.id("input1"));//报错 //进入id="frame"的frame中,定位id="div1"的div和id="input1"的输入框。 dr.switchTo().frame("frame"); dr.findElement(By.id("div1")); dr.findElement(By.id("input1")); //此时,没有跳出frame,如果定位default content中的元素也会报错。 dr.findElement(By.id("id1"));//报错 //跳出frame,进入default content;重新定位id="id1"的div dr.switchTo().defaultContent(); dr.findElement(By.id("id1"));
弹出窗口
//得到当前窗口的句柄 String currentWindow = dr.getWindowHandle(); //得到所有窗口的句柄 Set<String> handles = dr.getWindowHandles(); for(String handle : handles) { if(currentWindow.equals(handle)) continue; WebDriver window = dr.switchTo().window(handle); //... }
alert、confirm、prompt
getText()
得到它的文本值accept()
相当于点击它的"确认"dismiss()
相当于点击"取消"或者叉掉对话框sendKeys()
输入值
Alert alert = dr.switchTo().alert(); String text = alert.getText(); System.out.println(text); alert.dismiss();
Alert confirm = dr.switchTo().alert(); String text1 = confirm.getText(); confirm.accept();
Alert prompt = dr.switchTo().alert(); String text2 = prompt.getText(); prompt.sendKeys("jarvi"); prompt.accept();
下拉框
页面:
<div id="car-menu"> <h2>品牌选择</h2> <select name="cars",id="select"> <option value="volvo">Volvo</option> <option value="saab">Saab</option> <option value="fiat" selected="selected">Fiat</option> <option value="audi">Audi</option> <option value="bmw">BMW</option> <option value="Mercedes Benz ">Mercedes Benz </option> </select> </div>
代码:
Select selectCar = new Select(dr.findElement(By.name("cars"))); // 通过下拉列表中选项的索引选中第二项, selectCar.selectByIndex(4); // 通过可见文字“audi”选中相应项, selectengin.selectByVisibleText("audi");
拖放元素
WebElement ele = dr.findElement(By.id("item1")); WebElement tar = dr.findElement(By.id("drop")); (new Action(dr)).dragAndDrop(ele, tar).perform();
表格
下面这个实例按照原顺序输出表格中的内容:
WebElement table = driver.findElement(By.id("my-table")); List<WebElement> rows = table.findElements(By.tagName("tr")); for(WebElement row : rows) { // 列里面有"<th>"、"<td>"两种标签,所以分开处理。 List<WebElement> heads = row.findElements(By.tagName("th")); for(WebElement head : heads) { System.out.print(head.getText()); System.out,print(" "); } List<WebElement> cols = row.findElements(By.tagName("td")); for(WebElement col : cols) { System.out.print(col.getText()); System.out,print(" "); } System.out,println(); }
Cookies
// 增加一个name = "name",value="value"的cookie Cookie cookie = new Cookie("name", "value"); dr.manage().addCookie(cookie); // 得到当前页面下所有的cookies,并且输出它们的所在域、name、value、有效日期和路径 Set<Cookie> cookies = dr.manage().getCookies(); System.out.println(String .format("Domain -> name -> value -> expiry -> path")); for (Cookie c : cookies) System.out.println(String.format("%s -> %s -> %s -> %s -> %s", c.getDomain(), c.getName(), c.getValue(), c.getExpiry(),c.getPath())); // 删除cookie有三种方法 // 第一种 通过cookie的name dr.manage().deleteCookieNamed("CookieName"); // 第二种 通过Cookie对象 dr.manage().deleteCookie(cookie); // 第三种 全部删除 dr.manage().deleteAllCookies();
等待
明确等待
假设被测页面实现了这样的一种效果:点击click按钮4秒钟后,页面上会出现一个蓝色的div块。需要写一段自动化脚本去捕获这个出现的div,然后高亮它。
WebDriverWait wait = new WebDriverWait(dr, 10); wait.until(new ExpectedCondition<WebElement>() { public WebElement apply(WebDriver d) { return d.findElement(By.cssSelector(".blue_box")); } }
代码WebDriverWait类的构造方法接受了一个WebDriver对象和一个等待最长时间(10秒)。然后调用until方法,其中重写了ExpectedCondition接口中的apply方法,让其返回一个WebElement,即加载完成的元素。默认情况下,WebDriverWait每500毫秒调用一次ExpectedCondition,直到有成功的返回,当然如果超过设定的值还没有成功的返回,将抛出异常。
隐性等待
隐性等待是指当要查找元素,而这个元素没有马上出现时,告诉WebDriver查询Dom一定时间。默认值是0,但是设置之后,这个时间将在WebDriver对象实例整个生命周期都起作用。
上面的代码可改为如下代码:
1. // 设置10秒 2. dr.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
截图
// 这里等待页面加载完成 Thread.sleep(5000); // 下面代码是得到截图并保存在D盘下 File screenShotFile = ((TakesScreenshot) dr).getScreenshotAs(OutputType.FILE); FileUtils.copyFile(screenShotFile, new File("E:/软件测试课程/selenium/test.png"));
鼠标键盘模拟
单一操作
//新建一个action Actions action=new Actions(driver); //操作 WebElement element = dr.findElement(By.id("test")); WebElement element1 = dr.findElement(By.id("su")); action.sendKeys(element,"test").perform(); action.moveToElement(element1); action.click().perform();
组合操作
(new Actions(dr)).dragAndDrop(dr.findElement(By.id(item)), target).perform(); Action dragAndDrop = builder.clickAndHold(someElement) .moveToElement(otherElement) .release(otherElement) .build().perform();
其他鼠标或键盘操作方法可以具体看一下API里面的org.openqa.selenium.interactions.Actions
类。
其它
firefox代理
String PROXY = "localhost:8080";//如果不是本机,localhost替换成IP地址 org.openqa.selenium.Proxy proxy = new org.openqa.selenium.Proxy(); proxy.setHttpProxy(PROXY) .setFtpProxy(PROXY) .setSslProxy(PROXY); DesiredCapabilities cap = new DesiredCapabailities(); cap.setPreference(CapabilityType.PROXY, proxy); WebDriver driver = new FirefoxDriver(cap);
启用firefox禁用的功能
FirefoxProfile profile = new FirefoxProfile(); profile.setEnableNativeEvents(true); WebDriver driver = new FirefoxDriver(profile);
临时指定插件
有时需要临时让启动的firefox带一个插件,如firebug,来定位问题等。首先要下载这个插件的xpi安装包。剩下的就让selenium webdriver来完成,如下:
FirefoxProfile firefoxProfile = new FirefoxProfile(); firefoxProfile.addExtension(file); //避免启动画面 firefoxProfile.setPreference("extensions.firebug.currentVersion", "1.10.1"); WebDriver driver = new FirefoxDriver(firefoxProfile);
注
部分内容来自SE225软件测试课程课件第8章--GUI测试工具。