在 Selenium 中通过 XPath 查找元素
为什么需要 Find Element(s) 命令?
与网页交互需要用户定位网页元素。Find Element 命令用于唯一标识网页中的一个网页元素。而 Find Elements 命令用于唯一标识网页中的网页元素列表。有多种方法可以唯一标识网页中的网页元素,例如 ID、名称、类名、链接文本、部分链接文本、标签名和 XPATH。
FindElement 命令语法
WebElement elementName = driver.findElement(By.LocatorStrategy("LocatorValue"));
Selenium Find Element 命令将 By 对象作为参数,并返回一个 Selenium 中的 WebElement 列表类型对象。By 对象又可以与各种定位策略一起使用,例如通过 ID Selenium、名称、类名、XPATH 等查找元素。下面是 Selenium web driver 中 FindElement 命令的语法。
定位策略可以是以下任何值。
- ID
- Selenium 通过名称查找元素
- 类名
- 标签名
- 链接文本
- 部分链接文本
- XPATH
定位器值是用于识别网页元素的唯一值。开发人员和测试人员有责任确保网页元素可以使用某些属性(如 ID 或名称)唯一识别。
示例
WebElement loginLink = driver.findElement(By.linkText("Login"));
示例:在 Selenium 中查找元素
以下应用程序用于演示目的
https://demo.guru99.com/test/ajax.html
场景
步骤 1: 打开 AUT
步骤 2: 查找并点击单选按钮
package com.sample.stepdefinitions; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; public class NameDemo { public static void main(String[] args) { // TODO Auto-generated method stub System.setProperty("webdriver.chrome.driver", "D:\\3rdparty\\chrome\\chromedriver.exe"); WebDriver driver = new ChromeDriver(); driver.manage().window().maximize(); driver.get("https://demo.guru99.com/test/ajax.html"); // Find the radio button for “No” using its ID and click on it driver.findElement(By.id("no")).click(); //Click on Check Button driver.findElement(By.id("buttoncheck")).click(); } }
FindElements 命令语法
List<WebElement> elementName = driver.findElements(By.LocatorStrategy("LocatorValue"));
Selenium 中的 FindElements 命令将 By 对象作为参数,并返回一个网页元素列表。如果没有使用给定的定位策略和定位器值找到元素,它将返回一个空列表。下面是 find elements 命令的语法。
示例
List<WebElement> listOfElements = driver.findElements(By.xpath("//div"));
示例:在 Selenium 中查找多个元素
场景
步骤 1: 打开待测应用程序的 URL
步骤 1: 查找单选按钮的文本并将其打印到输出控制台
package com.sample.stepdefinitions; import java.util.List; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; public class NameDemo { public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "X://chromedriver.exe"); WebDriver driver = new ChromeDriver(); driver.get("https://demo.guru99.com/test/ajax.html"); List<WebElement> elements = driver.findElements(By.name("name")); System.out.println("Number of elements:" +elements.size()); for (int i=0; i<elements.size();i++){ System.out.println("Radio button text:" + elements.get(i).getAttribute("value")); } } }
Find element 与 Find elements
以下是 find element 和 find elements 命令的主要区别。
查找元素 | 查找多个元素 |
---|---|
如果使用相同的定位器找到多个网页元素,则返回第一个网页元素。 | 返回网页元素列表 |
如果没有与定位策略匹配的元素,则抛出 NoSuchElementException 异常 | 如果没有与定位策略匹配的网页元素,则返回一个空列表。 |
通过 XPath 查找元素将只查找一个网页元素。 | 它将查找与定位策略匹配的元素集合。 |
不适用 | 每个网页元素都像数组一样从 0 开始编号。 |
摘要
- Find Element 命令返回与网页中第一个元素匹配的网页元素。
- Find Elements 命令返回与条件匹配的网页元素列表。
- Selenium 中的 Find Element by XPath 命令如果找不到与条件匹配的元素,则抛出 NoSuchElementException 异常。
- Selenium 中的 Find Elements 命令如果没有与条件匹配的元素,则返回一个空列表。