findElement() 和 findElements() 方法之间有什么区别?

domprogrammingjava programming 更新于 2026/1/27 21:32:17

findElement() 和 findElements() 方法尝试在 DOM 中搜索元素。

它们之间的区别如下 −

sl.no.findElement()
findElements()
1
返回第一个与定位器匹配的 Web 元素。
返回所有与定位器匹配的 Web 元素。
2
语法 − WebElement button = webdriver.findElement(By.name("<<Name value>>"));
语法 − List<WebElement> buttons = webdriver.findElements(By.name("<<Name value>>"));
3
如果没有匹配的 Web 元素,则抛出 NoSuchElementException
如果没有匹配的元素,则返回空列表。

示例

Using findElements ().

import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
public class RowFindElements {
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver", "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      String url = "https://www.tutorialspoint.com/plsql/plsql_basic_syntax.htm";
      driver.get(url);
      driver.manage().window().maximize();
      driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
      // 使用附加索引的 xpath 从表的第 1 行获取值,使用 findElements() ,      返回一个列表
      List<WebElement> rows = driver.findElements(By.xpath("//table/tbody/tr[2]/td"));
      System.out.println(“The number of values in row 2 is “+ rows.size());
      driver.close();
   }
}

示例

Using findElement ()

import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
public class CssTagname {
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver",    "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      String url = "https://www.tutorialspoint.com/index.htm";
      driver.get(url);
      driver.manage().timeouts().implicitlyWait(12, TimeUnit.SECONDS);
      //使用 id 标签名 属性组合进行 CSS 表达式
      //并通过 findElement() 获取元素
      driver.findElement(By.cssSelector("input[name=’search’]")).
      sendKeys("Selenium");
      driver.close();
   }
}