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


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

它们之间的区别如下 −

序号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。
如果没有匹配的元素,则返回空列表。

示例

使用 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://tutorialspoint.com/plsql/plsql_basic_syntax.htm";
      driver.get(url);
      driver.manage().window().maximize();
      driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
      // xpath with index appended to get the values from the row 1of table using findElements() ,       which returns a list
      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();
   }
}

示例

使用 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://tutorialspoint.com/index.htm";
      driver.get(url);
      driver.manage().timeouts().implicitlyWait(12, TimeUnit.SECONDS);
      //Using id tagname attribute combination for css expression
      //and get the element from findElement()
      driver.findElement(By.cssSelector("input[name=’search’]")).
      sendKeys("Selenium");
      driver.close();
   }
}

更新于: 2020-06-10

915 次浏览

开启你的 职业生涯

通过完成课程获得认证

开始
广告
© . All rights reserved.