第1章 aiuoupoup(2 / 5)

p://www.forexample.com“);

8

9 List<WebElement> allInputs = driver.findElements(By.tagName(“input“));

10

11 //只打印所有文本框的值

12

13 for(WebElement e: allInputs){

14

15 if (e.getAttribute(“type”).equals(“text”)){

16

17 System.out.println(e.getText().toString());//打印出每个文本框里的值

18

19 }

20

21 }

22

23 }

24

25 }

复制代码

4. By.className()

className属性是利用元素的css样式表所引用的伪类名称来进行元素查找的方法。对于任何HTML页面的元素来说,一般程序员或页面设计师会给元素直接赋予一个样式属性或者利用css文件里的伪类来定义元素样式,使元素在页面上显示时能够更加美观。一般css样式表可能会长成下面这个样子:

复制代码

1 .buttonStyle{

2

3 width: 50px;

4

5 height: 50px;

6

7 border-radius: 50%;

8

9 margin: 0% 2%;

10

11 }

复制代码

定义好后,就可以在页面元素中引用上述定义好的样式,如下:

1 <button name=“sampleBtnName“ id=“sampleBtnId“ class=“buttonStyle“>I'm Button</button>

如果此时我们要通过className属性来查找该button并操作它的话,就可以使用className属性了,代码如下:

复制代码

1 public class SearchElementsByClassName{

2

3 public static void main(String[] args){

4

5 WebDriver driver = new FirefoxDriver();

6

7 driver.get(“http://www.forexample.com“);

8

9 WebElement searchBox = driver.findElement(By.className(“buttonStyle“));

10

11 searchBox.sendKeys(“Hello, world“);

12

13 }

14

15 }

复制代码

注意:使用className来进行元素定位时,有时会碰到一个元素指定了若干个class属性值的“复合样式”的情况,如下面这个button:<button id=“J_sidebar_login“ class=“btn btn_big btn_submit“ type=“submit“>登录</button>。这个button元素指定了三个不同的css伪类名作为它的样式属性值,此时就必须结合后面要介绍的cssSelector方法来定位了,稍后会有详细例子。

5. By.linkText()

这个方法比较直接,即通过超文本链接上的文字信息来定位元素,这种方式一般专门用于定位页面上的超文本链接。通常一个超文本链接会长成这个样子:

1 <a href=“/intl/en/about.html“>About Google</a&