在 Selenium Webdriver 中查找子元素中的元素。
seleniumautomation testingtesting tools更新于 2026/1/6 19:22:17
我们可以使用 Selenium Webdriver 查找子元素中的元素。首先,我们需要借助 id、class、name、xpath 或 css 等定位器来识别元素。然后,我们必须使用 findElements(By.xpath()) 方法识别子元素。
我们可以通过将子元素与元素进行本地化,然后将表达式 (./child::*) 作为参数传递给 findElements(By.xpath()) 来识别元素中的子元素。
语法
element.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 SubElement{
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://www.tutorialspoint.com/about/about_careers.htm");
// 识别元素
WebElement t=driver.findElement(By.xpath("//ul[@class='toc chapters']"));
// 使用 xpath 中的 ./child::* 表达式识别子元素
List c = t.findElements(By.xpath("./child::*"));
// 迭代子元素
for ( WebElement i : c ) {
//getTagName() to get tag of sub-elements
System.out.println(i.getTagName());
}
driver.close();
}
}
输出


