如何在 Selenium 2 中验证某个元素是否存在?

seleniumautomation testingtesting tools

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

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

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

让我们验证一下突出显示的文本是否存在于页面上。 −

示例

Code Implementation with 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://www.tutorialspoint.com/index.htm");
      String str = "You are browsing the best resource for Online Education";
      // 识别元素
      List<WebElement> m= driver.findElements(By.xpath("//*[contains(text(),'You are browsin')]"));
      // 验证大小
      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://www.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();
   }
}

输出


相关文章