在 Selenium Webdriver 中查找子元素中的元素。
我们可以使用 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://tutorialspoint.com/about/about_careers.htm");
// identify element
WebElement t=driver.findElement(By.xpath("//ul[@class='toc chapters']"));
//identify sub-elements with ./child::* expression in xpath
List c = t.findElements(By.xpath("./child::*"));
// iterate sub-elements
for ( WebElement i : c ) {
//getTagName() to get tag of sub-elements
System.out.println(i.getTagName());
}
driver.close();
}
}输出

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