【javawb】使用findElements方法来定位元素

findElements()方法会返回匹配指定查询条件的WebElements的集合(即:可以得到匹配指定规则的集合。如果没有找到则返回为空

JAVA实例代码:

package com.example.tests;

import static org.junit.Assert.*;

import java.util.*;

import org.junit.*;

import org.openqa.selenium.*;

import org.openqa.selenium.ie.InternetExplorerDriver;

public class Selenium2

{

@Test

public void test()

{

WebDriver driver = new InternetExplorerDriver();

driver.get("http://www.baidu.com");

List<WebElement> links = driver.findElements(By.cssSelector("#nv a"));

//验证链接数量 

assertEquals(10, links.size());

//打印href属性 

for (int i = 0; i < links.size(); i++)

{

System.out.println(links.get(i).getAttribute("href"));

}

driver.close();

}

u 定位链接

WebElement gmailLink = driver.findElement(By.linkText("GMail"));

assertEquals("http://mail.google.com/",gmailLink.getAttribute("href"));

通过部分链接名定位链接

WebElement inboxLink =   

driver.findElement(By.partialLinkText("Inbox"));

System.out.println(inboxLink.getText());     

u 通过标签名称定位元素

WebElement table = driver.findElement(By.id("summaryTable"));

List<WebElement> rows = table.findElements(By.tagName("tr"));

assertEquals(10, rows.size());

u 使用CSS选择器定位元素

 使用绝对路径定位元素:

WebElement userName = driver.findElement(By.cssSelector("html body  div div form input"));

使用相对路径定位元素:

当我们使用CSS选择器来查找元素的时候,我们可以使用class属性来定位元素。我们可以先指定一个HTML的标签,然后加一个“.”符号,跟上class属性的值,方法如下:

WebElement loginButton =

driver.findElement(By.cssSelector("input.login"));

ID选择器定位元素:

先指定一个HTML标签,然后加上一个“#”符号,跟上id的属性值,如下所示:

WebElement userName =  

driver.findElement(By.cssSelector("input#username"));

使用其他属性的选择器定位元素:

使用name选择器:

WebElement userName =  

driver.findElement(By.cssSelector("input[name=username]"));

使用alt选择器:

WebElement previousButton =   

driver.findElement(By.cssSelector("img[alt='Previous']"));

使用多个属性选择器定位元素:

WebElement previousButton = driver.findElement(By.cssSelector("input[type='submit'][value='Login']"));

u 使用XPath定位元素

使用绝对路径:

WebElement userName =

driver.findElement(By.xpath("html/body/div/div/form/input"));

使用相对路径:

处于DOM中第一个<input>元素:

WebElement userName = driver.findElement(By.xpath("//input"));

使用索引定位DOM中的第二个<input>元素:

WebElement passwd=driver.findElement(By.xpath("//input[2]"));

使用Xpath和属性值定位元素:

WebElement previousButton = driver.findElement

(By.xpath("//input[@type='submit'and @value='Login']"));

u 使用jQuery选择器

以百度首页为例,百度首页没有jQuery库。我们想定位百度导航栏上面的所有超链接元素,并输出结果。

package com.example.tests;

import static org.junit.Assert.*;

import java.util.*;

import org.junit.*;

import org.openqa.selenium.*;

import org.openqa.selenium.ie.InternetExplorerDriver;

public class Selenium2 {

WebDriver driver = new InternetExplorerDriver();

JavascriptExecutor jse = (JavascriptExecutor)driver;

@Test

public void jQueryTest() {

driver.get("http://www.baidu.com/");

injectjQueryIfNeeded();

List<WebElement> elements =

(List<WebElement>)jse.executeScript

("return jQuery.find('#nv a')");

assertEquals(7,elements.size()); //验证超链接的数量 

for (int i = 0; i < elements.size(); i++) {

System.out.print(elements.get(i).getText() + "");

}

driver.close();

}

private void injectjQueryIfNeeded() {

if (!jQueryLoaded())

injectjQuery();

}

//判断是已加载jQuery

public Boolean jQueryLoaded() {

Boolean loaded;

try {

loaded = (Boolean)jse.executeScript("return " +

"jQuery()!=null");

} catch (WebDriverException e) {

loaded = false;

}

return loaded;

}

//通过注入jQuery

public void injectjQuery() {

jse.executeScript(" var headID = "

+"document.getElementsByTagName(\"head\")[0];"

+ "var newScript = document.createElement('script');"

+ "newScript.type = 'text/javascript';"

+ "newScript.src = "

+"'http://ajax.googleapis.com/ajax/"

+"libs/jquery/1.7.2/jquery.min.js';"

+ "headID.appendChild(newScript);");

}

}

injectjQueryIfNeeded()方法首先通过jQueryLoaded()方法来判断网页中是否加有jQuery对象。如果没有,再调用injectjQuery()方法通过增加一个<Script>元素来实时加载jQuery库,参考的是Google在线库,可修改例子中的版本,使用最新的jQuery版本。

u 定位表格的行和列

表格相关的页面元素

package com.example.tests;

import static org.junit.Assert.*;

import java.util.*;

import org.junit.*;

import org.openqa.selenium.*;

import org.openqa.selenium.ie.InternetExplorerDriver;

public class Selenium2

{

WebDriver driver = new InternetExplorerDriver();

JavascriptExecutor jse = (JavascriptExecutor)driver;

@Test

public void tableTest()

{

driver.get

("http://www.w3school.com.cn/html/html_tables.asp");

//首先得到所有tr的集合 

List<WebElement> rows =

driver.findElements(By.cssSelector(".dataintable tr"));

//验证表格的行数 

assertEquals(11,rows.size());

//打印出所有单元格的数据 

for (WebElement row : rows)

{

//得到当前trtd的集合 

List<WebElement> cols =

row.findElements(By.tagName("td"));

for (WebElement col : cols)

{

System.out.print(col.getText());//得到td里的文本 

}

System.out.println();

}

driver.close();

}

}

u 检查元素的文本

@Test

public void testElementText()

{

//取得元素

WebElement message = driver.findElement(By.id("message"));

//得到元素文本

String messageText = message.getText();

//验证文本为"Click on me and mycolor will change"

assertEquals("Click on me and my color will change",  messageText);

//获得area元素

WebElement area = driver.findElement(By.id("area"));

//验证文本为"Div's Text\nSpan's Text"

assertEquals("Div's Text\nSpan's Text",area.getText());

}

WebElement中的getText()方法返回元素的innerText属性。所以元素里面如果有子节点一样也会被反回出来

也可以使用JavaString API方法如contains()startsWith()endsWith()来进行部分匹配。方法如下:

assertTrue(messageText.contains("color"));

assertTrue(messageText.startsWith("Click on"));

assertTrue(messageText.endsWith("will change"));

u 检查元素的属性值

此处需要使用getAttribute()方法来检查元素的属性。

创建一个测试,定位元素再检查它的属性,方法如下:

@Test

public void testElementAttribute()

{

WebElement message = driver.findElement(By.id("message"));

assertEquals("justify",message.getAttribute("align"));

}

此例子中验证了元素的属性align的值是否为justify

u 检查元素的CSS属性值

让我们创建一个测试,读取元素的CSS的width属性并验证它的值。

@Test

public void testElementStyle()

{

WebElement message = driver.findElement(By.id("message"));

String width = message.getCssValue("width");

assertEquals("150px",width);

}

u 针对鼠标和键盘事件使用高级的用户交互API

Selenium WebDriver高级用户交互API允许我们通过使用Actions类执行从键盘事件到简单或复杂的鼠标事件,如拖拽操作,按住一个按键然后执行鼠标操作,创建一个复杂的事件链就像用户真正的在手动操作一样。

我们创建一个测试使用Ctrl按键来选择表格的多个行。我们可以先选择第一行,然后按住ctrl键,再选择另一行后释放ctrl键。这样就可以选择所需要的行。

@Test

public void testRowSelectionUsingControlKey()

{

List<WebElement> tableRows = driver.findElements

(By.xpath("//table[@class='iceDatTbl']/tbody/tr"));

//Select second and fourth row from table using Control Key.

//Row Index start at 0

Actions builder = new Actions(driver);

builder.click(tableRows.get(1)).keyDown(Keys.CONTROL).click(tableRows.get(3)).keyUp(Keys.CONTROL).build().perform();

//Verify Selected Row table shows two rows selected

List<WebElement> rows = driver.findElements

(By.xpath("//div[@class='icePnlGrp  exampleBox']/table[@class='iceDatTbl']/tbody/tr"));

assertEquals(2,rows.size());

}

首先创建一个Actions的实例,再调用相应的事件方法,然后调用build()方法,建立这么一组操作方法链,最后调用perform()来执行。

u 在元素上执行双击操作

package com.example.tests;

import static org.junit.Assert.*;

import org.junit.*;

import org.openqa.selenium.*;

import org.openqa.selenium.firefox.FirefoxDriver;

import org.openqa.selenium.interactions.Actions;

public class Selenium2 {

WebDriver driver = new FirefoxDriver();

@Test

public void actionsTest() {

driver.get("D:\\demo\\DoubleClickDemo.html");

WebElement message = driver.findElement(By.id("message"));

// 验证初始字体为14px

assertEquals("14px", message.getCssValue("font-size"));

Actions builder = new Actions(driver);

builder.doubleClick(message).build().perform();

// 验证点击后字体变为20px

assertEquals("20px", message.getCssValue("font-size"));

driver.close();

}

}

当鼠标双击的时候触发了字体变化的事件,我们可以使用doubleClick()来模拟真实的双击。

u 执行拖拽操作

package com.example.tests;

import static org.junit.Assert.*;

import org.junit.*;

import org.openqa.selenium.*;

import org.openqa.selenium.ie.InternetExplorerDriver;

import org.openqa.selenium.interactions.Actions;

public class Selenium2 {

@Test

public void testDragDrop() {

WebDriver driver = new InternetExplorerDriver();

driver.get("D:\\demo\\DragAndDrop.html");

WebElement source = driver.findElement(By.id("draggable"));

WebElement target = driver.findElement(By.id("droppable"));

Actions builder = new Actions(driver);

builder.dragAndDrop(source, target).perform();

try {

assertEquals("Dropped!", target.getText());

} catch (Error e) {

e.printStackTrace();

}finally{

driver.close();

}

}

}

拖拽一个元素到另一个元素再放下,我们需要先定位返些元素(原元素,目标元素)然后作为参数传给dragAndDrop()

u 执行JavaScript代码

package com.example.tests;

import static org.junit.Assert.*;

import org.junit.*;

import org.openqa.selenium.*;

import org.openqa.selenium.ie.InternetExplorerDriver;

public class Selenium2 {

@Test

public void testJavaScriptCalls() {

WebDriver driver = new InternetExplorerDriver();

driver.get("http://www.baidu.com");

JavascriptExecutor js = (JavascriptExecutor) driver;

String title = (String) js.executeScript("return document.title");

assertEquals("百度一下,你就知道", title);

long links = (Long) js.executeScript("var links = "

+ "document.getElementsByTagName('A'); "

+ "return links.length");

assertEquals(26, links);

driver.close();

}

}

从javaScript代码中迒回数据我们需要使用return关键字。基亍迒回值癿类型,我们需要对executeScript()方法迕行转型。对亍带小数点癿值,使用Double类型,非小数值可以使用Long类型,布尔值可以使用Boolean类型,如果迒回癿是HTML节点,可以使用 WebElement类型,文本值,可以使用String类型。如果迒回癿是对象列表,基亍对象类型癿仸何值都可以。

u 使用Selenium WebDriver进行截图

Selenium WebDriver提供了TakesScreenshot接口来捕捉网页的全屏。返可以在测试执行遇到异常错误时候将屏幕戔叏下来,可以知道弼时収生了什么。我们也可以在验证元素状态,显示值是某个操作完成后状态迕行屏。

package com.example.tests;

import java.io.File;

import org.apache.commons.io.FileUtils;

import org.junit.*;

import org.openqa.selenium.*;

import org.openqa.selenium.ie.InternetExplorerDriver;

public class Selenium2 {

@Test

public void testTakesScreenshot() {

WebDriver driver = new InternetExplorerDriver();

driver.get("http://www.baidu.com");

try {

File srcFile = ((TakesScreenshot)driver).

getScreenshotAs(OutputType.FILE);

FileUtils.copyFile

(srcFile,new File("d:\\screenshot.png"));

} catch (Exception e) {

e.printStackTrace();

}

driver.close();

}

}

TakesScreenshot接口提供了getScreenshotAs()方法来捕捉屏幕。上面的例子中,我们指定了OutputType.FILE作为参数传递给getScreenshoAs()方法,告诉它将截取的屏幕以文件形式返回。

使用org.apache.commons.io.FileUtils类中的copyFile()方法来保存getScreenshot()返回的文件对象。TakesScreenshot接口依赖于浏览器中的API来捕捉屏幕。所以在HtmlUnit Driver中不支持这样使用。

u 将浏览器窗口最大化

package com.example.tests;

import org.junit.*;

import org.openqa.selenium.*;

import org.openqa.selenium.ie.InternetExplorerDriver;

public class Selenium2 {

@Test

public void testTakesScreenshot() {

WebDriver driver = new InternetExplorerDriver();

driver.get("http://www.baidu.com");

driver.manage().window().maximize(); 

driver.close();

}

}

u 自动选择下拉列表

package com.example.tests;

import static org.junit.Assert.*;

import org.junit.*;

import org.openqa.selenium.*;

import org.openqa.selenium.firefox.FirefoxDriver;

import org.openqa.selenium.support.ui.Select;

public class Selenium2 {

@Test

public void testDropdown() {

WebDriver driver = new FirefoxDriver();

driver.get("D:\\demo\\Droplist.html");

//得到下拉列表框 

Select make =

new Select(driver.findElement(By.name("make")));

//验证下拉列表的不支持多选 

assertFalse(make.isMultiple());

//验证下拉列表的数量 

assertEquals(4,make.getOptions().size());

//命名用可见的本文来选择选项 

make.selectByVisibleText("Honda");

//通过value属性来选择选项 

make.selectByValue("Audi");

//通过索引来选择选项 

make.selectByIndex(2);

driver.close();

}

}

在执行面的例子时需要导入org.openqa.selenium.support.ui.Select类。首先创建一个Select癿对象,

isMultiple()用来判断是丌是多选下拉框。

Select类提供了3种方法来选择下拉选项

selectByVisibleText()selectByValue(),selectByIndex()

package com.example.tests;

import static org.junit.Assert.*;

import org.junit.*;

import org.openqa.selenium.*;

import org.openqa.selenium.firefox.FirefoxDriver;

import org.openqa.selenium.support.ui.Select;

public class Selenium2 {

@Test

public void testMultipleSelectLis() {

WebDriver driver = new FirefoxDriver();

driver.get("D:\\demo\\Droplist.html");

// 得到下拉列表框 

Select color = new Select(driver.findElement(By.name("color")));

// 验证下拉列表支持多选 

assertTrue(color.isMultiple());

// 验证下拉列表的数量 

assertEquals(4, color.getOptions().size());

// 使用可见的本文来选择选项 

color.selectByVisibleText("Black");

color.selectByVisibleText("Red");

color.selectByVisibleText("Silver");

// 通过可见的文本取消已选选项 

color.deselectByVisibleText("Silver");

// 通过value属性取消已选选项 

color.deselectByValue("red");

// 通过选项索引取消已选选项 

color.deselectByIndex(0);

}

}

u 检查下拉列表中的选项

检查单选的下拉框:

package com.example.tests;

import static org.junit.Assert.*;

import org.junit.*;

import org.openqa.selenium.*;

import org.openqa.selenium.firefox.FirefoxDriver;

import org.openqa.selenium.support.ui.Select;

public class Selenium2 {

@Test

public void testDropdown() {

WebDriver driver = new FirefoxDriver();

driver.get("D:\\demo\\Droplist.html");

//得到下拉列表框 

Select make =

new Select(driver.findElement(By.name("make")));

//验证下拉列表的不支持多选 

assertFalse(make.isMultiple());

//验证下拉列表的数量 

assertEquals(4,make.getOptions().size());

//使用可见的本文来选择选项 

make.selectByVisibleText("Honda");

assertEquals

("Honda",make.getFirstSelectedOption().getText());

//通过value属性来选择选项 

make.selectByValue("Audi");

assertEquals("Audi",

make.getFirstSelectedOption().getText());

//通过索引来选择选项 

make.selectByIndex(2);

assertEquals("BMW",

make.getFirstSelectedOption().getText());

}

}

检查多选的下拉框:

import static org.junit.Assert.*;

import java.util.*;

import org.junit.*;

import org.openqa.selenium.*;

import org.openqa.selenium.firefox.FirefoxDriver;

import org.openqa.selenium.support.ui.Select;

public class Selenium2 {

@Test

public void testMultipleSelectLis() {

WebDriver driver = new FirefoxDriver();

driver.get("D:\\demo\\Droplist.html");

//得到下拉列表框 

Select color = new Select(driver.findElement(By.name("color")));

//验证下拉列表支持多选 

assertTrue(color.isMultiple());

//验证下拉列表的数量 

assertEquals(4,color.getOptions().size());

//用可见的本文来选择选项 

color.selectByVisibleText("Black");

color.selectByVisibleText("Red");

color.selectByVisibleText("Silver");

//验证所选的选项 

List<String> exp_sel_options =

Arrays.asList(new String[] {"Black","Red","Silver"});

List<String> act_sel_options = new ArrayList<String>();

for(WebElement option:color.getAllSelectedOptions()){

act_sel_options.add(option.getText());

}

//验证选择的选项和我们期望的是一样的 

assertArrayEquals

(exp_sel_options.toArray(), act_sel_options.toArray());

//验证3个选项已经被选择了 

assertEquals(3, color.getAllSelectedOptions().size());

//通过可见的文本取消已选选项 

color.deselectByVisibleText("Silver");

assertEquals(2, color.getAllSelectedOptions().size());

//通过value属性取消已选选项 

color.deselectByValue("red");

assertEquals(1, color.getAllSelectedOptions().size());

//通过选项索引取消已选选项 

color.deselectByIndex(0);

assertEquals(0, color.getAllSelectedOptions().size());

}

}

如果只是单选的下拉列表,通过getFirstSelectedOption()就可以得到所选择的选项,再调用getText()就可以得到本文。如果是多选的下拉列表,使用getAllSelectedOptions()得到所有已选择的选项,此方法会返回元素的集合。使用assertArrayEquals()方法来对比期望和实际所选的选项是否正确。调用getAllSelectedOptions().size()方法来判断已选的下拉列表选项数量。如果想检查某一个选项是否被选择了,可以使用assertTrue(act_sel_options.contains("Red"))方法。

u 自动选择单选按钮

Selenium WebDriver的WebElement类支持单选按钮和按钮组。我们可以通过click()方法来选择单选按钮和取消选择,使用isSelect()方法来判断是否选中了单选按钮。

package com.example.tests;

import static org.junit.Assert.*;

import java.util.*;

import org.junit.*;

import org.openqa.selenium.*;

import org.openqa.selenium.firefox.FirefoxDriver;

public class Selenium2 {

@Test

public void testRadioButton() {

WebDriver driver = new FirefoxDriver();

driver.get("D:\\demo\\RadioButton.html");

//使用value值来定位单选按钮 

WebElement apple =

driver.findElement(By.cssSelector("input[value='Apple']"));

//检查是否已选择,如果没有则点击选择 

if(!apple.isSelected()){

apple.click();

}

//验证apple选项已经选中 

assertTrue(apple.isSelected());

//也可以得到所有的单选按钮 

List<WebElement> fruit =

driver.findElements(By.name("fruit"));

//查询Orange选项是否存在,如果存在则选择 

for(WebElement allFruit : fruit){

if(allFruit.getAttribute("value").equals("Orange")){

if(!allFruit.isSelected()){

allFruit.click();

assertTrue(allFruit.isSelected());

break;

}

}

}

}

}

u 自动选择多选项框

Selenium WebDriver的WebElement类也支持多选框。我们可以使用click()方法来选择和取消选择,使用isSelect()方法来判断是否选中。

package com.example.tests;

import static org.junit.Assert.*;

import org.junit.*;

import org.openqa.selenium.*;

import org.openqa.selenium.firefox.FirefoxDriver;

public class Selenium2 {

@Test

public void testRadioButton() {

WebDriver driver = new FirefoxDriver();

driver.get("D:\\demo\\checkbox.html");

//使用value值来选择单选按钮 

WebElement apple = driver.findElement

(By.cssSelector("input[value='Apple']"));

WebElement pear = driver.findElement

(By.cssSelector("input[value='Pear']"));

WebElement orange = driver.findElement

(By.cssSelector("input[value='Orange']"));

//检查是否已选择,如果没有则点击选择 

if(!apple.isSelected()){

apple.click();

}

if(!pear.isSelected()){

pear.click();

}

if(!orange.isSelected()){

orange.click();

}

//验证选项已经选中 

assertTrue(apple.isSelected());

assertTrue(pear.isSelected());

assertTrue(orange.isSelected());

//再次点击apple多选框,取消选择 

if(apple.isSelected()){

apple.click();

}

assertFalse(apple.isSelected());

 

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

py编程

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值