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.tw/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.tw/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 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始
廣告