通过 XPath FindElement Selenium
为什么需要“查找元素”命令?
与网页交互需要用户找到 Web 元素。“查找元素”命令用于唯一地标识网页中的(一个)Web 元素。而“查找元素”命令用于唯一地标识网页中的 Web 元素列表。有多种方法可以唯一地标识网页中的 Web 元素,例如 ID、名称、类名、链接文本、部分链接文本、标签名称和 XPATH。
FindElement 命令语法
WebElement elementName = driver.findElement(By.LocatorStrategy("LocatorValue"));
Selenium Find Element 命令以 By 对象为参数,返回一个列表 WebElement 类型的对象 Selenium. 依次按对象可以与各种定位器策略一起使用,例如按 ID 查找元素 Selenium、名称、类名、XPATH 等。下面是 FindElement 命令的语法 Selenium 网络驱动程序。
定位器策略可以是下列任意值。
- ID
- Selenium 按名称查找元素
- 班级名称
- 标签名
- 链接文本
- 部分链接文本
- 路径
定位器值是可用于识别 Web 元素的唯一值。开发人员和测试人员有责任确保 Web 元素可使用某些属性(例如 ID 或名称)进行唯一识别。
计费示例:
WebElement loginLink = driver.findElement(By.linkText("Login"));
示例:在以下位置查找元素 Selenium
以下应用程序用于演示目的
https://demo.guru99.com/test/ajax.html
场景:
步骤1: 打开自动
步骤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 命令以 By 对象为参数并返回 Web 元素列表。如果使用给定的定位器策略和定位器值未找到任何元素,则返回空列表。以下是 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")); } } }
查找元素 Vs 查找元素
以下是查找元素和查找元素命令之间的主要区别。
查找元素 | 查找元素 |
---|---|
如果使用相同的定位器找到多个 Web 元素,则返回第一个 Web 元素 | 返回 Web 元素列表 |
如果没有元素符合定位器策略,则抛出异常 NoSuchElementException | 如果没有符合定位器策略的 Web 元素,则返回空列表 |
通过 XPath 查找元素只会找到一个 Web 元素 | 它将找到符合定位器策略的元素集合。 |
不适用 | 每个 Web 元素都用从 0 开始的数字进行索引,就像数组一样 |
结语
- 查找元素命令返回与网页内第一个元素匹配的 Web 元素。
- 查找元素命令返回符合条件的 Web 元素列表。
- 通过 XPath 查找元素 Selenium 如果命令没有找到符合条件的元素,则会抛出NoSuchElementException。
- 查找元素命令返回一个空列表 Selenium 如果没有符合条件的元素