在 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.com/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();
   }
}

输出

更新于: 18-Sep-2020

20K+ 浏览

开启你的 职业

完成课程并获得认证

开始
广告
© . All rights reserved.