Selenium 中的 Find Element 和 FindElements
方法 findElement 和 findElements 用于识别网页上的元素。这两个方法都可以与定位器一起使用,如 id、css、类、名称、xpath、css、链接文本、标记名称和部分链接文本。
方法 findElement 用于识别与作为该方法参数传入的定位器(与 By 对象一起使用)匹配的元素。如果没有匹配的元素,则抛出 NoSuchElementException。
方法 findElements 用于识别与作为该方法参数传入的定位器(与 By 对象一起使用)匹配的元素列表。如果没有匹配的元素,则返回一个空列表。
方法 findElement 返回一个 webelement,而方法 findElements 返回一个列表。如果有多个元素与定位器匹配,则 findElement 方法只会返回第一个匹配的元素(从页面左上角开始)。
语法
List<WebElement> e = driver.findElements(By.className("txt"));
WebElement elm = driver.findElement(By.className("txt"));示例
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
import java.util.List;
public class ElementLocator{
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver",
"C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
WebDriver driver = new ChromeDriver();
//implicit wait
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
//URL launch
driver.get("https://tutorialspoint.com/index.htm");
//identify all links with findElements
List m = driver.findElements(By.tagName("a"));
//link counts
int st = m.size();
System.out.println("Number of links: " + s);
//identify a link
WebElement n = driver.
findElement(By.xpath("//a[@title='Job @ Tutorials Point']"));
//get link text
String s= n.getText();
System.out.println("Text is : " + s);
driver.quit();
}
}输出

广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP