在 selenium 中定位 WebElements 的子節點。
我們可以使用 Selenium 網頁驅動程式定位 Web 元素的子節點。首先,我們需要使用任何定位器(如 ID、類、名稱、xpath 或 css)標識父元素。然後,我們必須使用 **findElements(By.xpath())** 方法識別子節點。
我們可以透過以下方法從父級識別子節點:用父級對其進行定位,然後將( ./child::*) 作為引數傳遞給 **findElements(By.xpath())**
語法−
parent.findElements(By.xpath("./child::*"))
讓我們識別下面 html 程式碼中 ul 節點的子節點文字 -

示例
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;
public class ChildNodes{
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver","C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
driver.get("https://tutorialspoint.tw/about/about_careers.htm");
// identify element
WebElement t=driver.findElement(By.xpath("//ul[@class='toc chapters']"));
//identify child nodes with ./child::* expression in xpath
List<WebElement> c = t.findElements(By.xpath("./child::*"));
// iterate child nodes
for ( WebElement i : c ) {
//getText() to get text for child nodes
System.out.println(i.getText());}
driver.close();
}
}輸出

廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP