如何使用 WebDriver(Selenium 2)检查 DOM 是否具有类?


我们可以用 Selenium webdriver 检查 DOM 是否具有类。我们可以使用 findElements 方法来获取具有特定类的元素列表。然后将 By.classNameBy.xpathBy.cssSelector 作为参数传递给该方法。

我们将要搜索的类名作为参数传递给该方法。让我们研究下面的 html 代码以了解具有类值 toc chaptersul 元素。然后获取其子元素。

示例

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 ClassAttrb{
   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 with class attribute
      WebElement m=
      driver.findElements(By.xpath("//ul[@class='toc chapters']"));
      //identify children
      List<WebElement> ch = m.findElements(By.xpath("./child::*"));
      // iterate through sub elements
      for ( WebElement i : ch ) {
         // get text for children
         System.out.println(i.getText());
      }
      driver.close();
   }
}

输出

更新日期:2021-02-01

329 浏览量

开启您的职业生涯

完成课程获得认证

开始
广告
© . All rights reserved.