如何在Selenium 2中验证元素不存在?


我们可以验证Selenium webdriver中元素是否存在。为此,我们将使用`getPageSource`方法获取整个页面源代码。因此,我们可以获取完整的页面源代码并检查元素的文本是否存在。

我们还可以使用`findElements`方法和任何定位器(例如xpath、CSS等)来识别匹配的元素。`findElements`返回一个元素列表。

我们将借助`size`方法计算列表返回的元素数量。如果`size`的值大于0,则元素存在;如果小于0,则元素不存在。

让我们验证页面上是否存在突出显示的文本:

示例

使用`findElements()`的代码实现。

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;
import java.util.List;
public class ExistElements{
   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/index.htm");
      String str = "You are browsing the best resource for Online Education";
      // identify elements
      List<WebElement> m= driver.findElements(By.xpath("//*[contains(text(),'You are browsin')]"));
      // verify size
      if ( m.size() > 0){
         System.out.println("Text: " + str + " is present. ");
      }
      else{
         System.out.println("Text: " + str+ " is not present. ");
      }
      driver.quit();
   }
}

示例

使用`getPageSource`的代码实现。

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 ElementExistPgSource{
   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/index.htm");
      String str = "You are browsing the best resource for Online Education";
      //get page source
      if ( driver.getPageSource().contains("You are browsin")){
         System.out.println("Text: " + str + " is present. ");
      }
      else{
         System.out.println("Text: " + str + " is not present. ");
      }
      driver.quit();
   }
}

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

输出

更新于:2021年2月1日

6K+ 次浏览

开启你的职业生涯

完成课程获得认证

开始学习
广告