如何使用Selenium / Java验证页面中元素的存在

时间:2014-11-14 21:05:42

标签: java selenium verify

我试图找出一种方法来查看某个元素是否存在于页面上。

这是我到目前为止所做的。

但是,如果元素不存在,则抛出异常,脚本将停止。

有人能帮我找到更好的方法吗?

//Checking navbar links
        System.out.println("=======================");
        System.out.println("Navbar link checks");
    //Checking for Web link element in Nav bar
        if(driver.findElement(By.xpath("/html/body/div[2]/div[1]/div[1]/ul/li[1]/a"))!= null){
            System.out.println("Web link in Navbar is Present");
            }else{
            System.out.println("Web link in Navbar is Absent");
            }
    //Checking for Images link element in Nav bar
        if(driver.findElement(By.xpath("/html/body/div[2]/div[1]/div[1]/ul/li[2]/a"))!= null){
            System.out.println("Images link in Navbar is Present");
            }else{
            System.out.println("Images link in Navbar is Absent");
            }
    //Checking for News link element in Nav bar
        if(driver.findElement(By.xpath("/html/body/div[2]/div[1]/div[1]/ul/li[3]/a"))!= null){
            System.out.println("News link in Navbar is Present");
            }else{
            System.out.println("News link in Navbar is Absent");
            }
    //Checking for Videos link element in Nav bar
        if(driver.findElement(By.xpath("/html/body/div[2]/div[1]/div[1]/ul/li[4]/a"))!= null){
            System.out.println("Videos link in Navbar is Present");
            }else{
            System.out.println("News link in Navbar is Absent");
            }
    //Checking for Maps link element in Nav bar
           if(driver.findElement(By.xpath("/html/body/div[2]/div[1]/div[1]/ul/li[5]/a"))!= null){
            System.out.println("Maps link in Navbar is Present");
            }else{
            System.out.println("Maps link in Navbar is Absent");
            }

2 个答案:

答案 0 :(得分:1)

您可以使用几种不同的方法。为此,我建议您使用findElements

if(driver.findElements(By.xpath("/html/body/div[2]/div[1]/div[1]/ul/li[1]/a"))!= 0)

答案 1 :(得分:1)

为避免异常,您可以简化编写自己的帮助程序,以处理NoSuchElementException并返回null

public class Helper {
    private static final WebDriver driver;
    public static WebElement findElement(By locator) {
        try {
            return driver.findElement(locator);
        } catch (NoSuchElementException notFound) {
            return null;
        }
    }

    // initialize Helper with your driver on startup
    public static init(WebDriver yourDriver) {
        driver = yourDriver;
    }
}

然后在你的代码中调用它:

//Checking for Web link element in Nav barl
WebElement element = Helper.findElement(By.xpath("my/complex/xpath"));
if(element == null) {
    System.out.println("My Element is Absent");
}