Selenium WebDriver - Test if element is present

2019-01-01 14:42发布

is there a way how to test if an element is present? Any findElement method would end in an exception, but that is not what I want, because it can be that an element is not present and that is okay, that is not a fail of the test, so an exception can not be the solution.

I've found this post: Selenium c# Webdriver: Wait Until Element is Present But this is for C# and I am not very good at it. Can anyone translate the code into Java? I am sorry guys, I tried it out in Eclipse but I don't get it right into Java code.

This is the code:

public static class WebDriverExtensions{
    public static IWebElement FindElement(this IWebDriver driver, By by, int timeoutInSeconds){

        if (timeoutInSeconds > 0){
            var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(timeoutInSeconds));
            return wait.Until(drv => drv.FindElement(by));
        }

        return driver.FindElement(by);
    }
}

20条回答
栀子花@的思念
2楼-- · 2019-01-01 15:09

Following are ways to check if an Web-Element isPresent or not :

I have used XPath as an Element Identifier/Locator, but you can use other locators as well.

Solution I :

public boolean isElementPresent(String xpathOfElement){
    try{
        driver.findElement(By.xpath(xpathOfElement));
        return true;
    }
    catch(NoSuchElementException e){
        return false;
    }
}

Solution II :

public boolean isElementPresent(String xpathOfElement){
    boolean isPresent = false;
    if(!driver.findElements(By.xpath(xpathOfElement)).isEmpty()){
        isPresent=true;
    }
    return isPresent;
}

Solution III :

public boolean isElementPresent(String xpathOfElement){
    return driver.findElements(By.xpath(xpathOfElement)).size() > 0;
}
查看更多
旧人旧事旧时光
3楼-- · 2019-01-01 15:11

I had the same issue. For me, depending on a user's permission level, some links, buttons and other elements will not show on the page. Part of my suite was testing that the elements that SHOULD be missing, are missing. I spent hours trying to figure this out. I finally found the perfect solution.

What this does, is tells the browser to look for any and all elements based specified. If it results in 0, that means no elements based on the specification was found. Then i have the code execute an if statement to let me know it was not found.

This is in C#, so translations would need to be done to Java. But shouldnt be too hard.

public void verifyPermission(string link)
{
    IList<IWebElement> adminPermissions = driver.FindElements(By.CssSelector(link));
    if (adminPermissions.Count == 0)
    {
        Console.WriteLine("User's permission properly hidden");
    }
}

There's also another path you can take depending on what you need for your test.

The following snippet is checking to see if a very specific element exists on the page. Depending on the element's existence I have the test execute an if else.

If the element exists and is displayed on the page, I have console.write let me know and move on. If the element in question exists, I cannot execute the test I needed, which is the main reasoning behind needing to set this up.

If the element Does Not exists, and is not displayed on the page. I have the else in the if else execute the test.

IList<IWebElement> deviceNotFound = driver.FindElements(By.CssSelector("CSS LINK GOES HERE"));
//if the element specified above results in more than 0 elements and is displayed on page execute the following, otherwise execute whats in the else statement
if (deviceNotFound.Count > 0 && deviceNotFound[0].Displayed){
    //script to execute if element is found
} else {
    //Test script goes here.
}

I know I'm a little late on the response to the OP. Hopefully this helps someone!

查看更多
只若初见
4楼-- · 2019-01-01 15:11

Personally, I always go for a mixture of the above answers and create a re-usable static Utility method that uses the size()<0 suggestion:

public Class Utility {
   ...
   public static boolean isElementExist(WebDriver driver, By by) {
      return driver.findElements(by).size() < 0;
   ...
}

This is neat, re-usable, maintainable ... all that good stuff ;-)

查看更多
残风、尘缘若梦
5楼-- · 2019-01-01 15:12

Use findElements instead of findElement.

findElements will return an empty list if no matching elements are found instead of an exception.

To check that an element is present, you could try this

Boolean isPresent = driver.findElements(By.yourLocator).size() > 0

This will return true if at least one element is found and false if it does not exist.

查看更多
琉璃瓶的回忆
6楼-- · 2019-01-01 15:13

if you are using rspec-Webdriver in ruby, you can use this script assuming that an element should really not be present and it is a passed test.

First, write this method first from your class RB file

class Test
 def element_present?
    begin
        browser.find_element(:name, "this_element_id".displayed?
        rescue Selenium::WebDriver::Error::NoSuchElementError
            puts "this element should not be present"
        end
 end

Then, on your spec file, call that method.

  before(:all) do    
    @Test= Test.new(@browser)
  end

 @Test.element_present?.should == nil

If your the element is NOT present, your spec will pass, but if the element is present , it will throw an error, test failed.

查看更多
素衣白纱
7楼-- · 2019-01-01 15:14

What about a private method that simply looks for the element and determines if it is present like this:

private boolean existsElement(String id) {
    try {
        driver.findElement(By.id(id));
    } catch (NoSuchElementException e) {
        return false;
    }
    return true;
}

This would be quite easy and does the job.

Edit: you could even go further and take a By elementLocator as parameter, eliminating problems if you want to find the element by something other than id.

查看更多
登录 后发表回答