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.tw/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(); } }
輸出
廣告