风华居 > 玄幻魔法 > 阅文测试书VIP > 第1章 aiuoupoup

第1章 aiuoupoup(1 / 7)

在使用selenium webdriver进行元素定位时,通常使用findElement或findElements方法结合By类返回的元素句柄来定位元素。其中By类的常用定位方式共八种,现分别介绍如下。

1. By.name()

假设我们要测试的页面源码如下:

<button id=“gbqfba“ aria-label=“Google Search“ name=“btnK“ class=“gbqfba“><span id=“gbqfsa“>Google Search</span></button>

当我们要用name属性来引用这个button并点击它时,代码如下:

View Code

2. By.id()

页面源码如下:

1 <button id=“gbqfba“ aria-label=“Google Search“ name=“btnK“ class=“gbqfba“><span id=“gbqfsa“>Google Search</span></button>

要引用该button并点击它时,代码如下:

复制代码

1 public class SearchButtonById {

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.id(“gbqfba“));

10

11 searchBox.click();

12

13 }

14

15 }

复制代码

3. By.tagName()

该方法可以通过元素的标签名称来查找元素。该方法跟之前两个方法的区别是,这个方法搜索到的元素通常不止一个,所以一般建议结合使用findElements方法来使用。比如我们现在要查找页面上有多少个button,就可以用button这个tagName来进行查找,代码如下:

复制代码

public class SearchPageByTagName{

public static void main(String[] args){

WebDriver driver = new FirefoxDriver();

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

List<WebElement> buttons = driver.findElements(By.tagName(“button“));

Sys

最新小说: 凡人同人之与韩老魔共存 卷王系统:开局把奶茶价格打下来 网游之死亡武侠 灵魂摆渡船 问道红尘 老祖别苟了,宇宙要没了 系统迟发五十年,老太退休成团宠 牙祭 御兽时代,我开局神级天赋 这个系统有点不太对