8

I am creating a script that involved searching for a record and then updating the record. On the search screen, the user has the option of viewing advanced search options. To toggle showing or hiding advanced search is controlled by one button.

<a title="Searches" href="javascript:expandFilters()"><img border="0" align="absmiddle" alt="Advanced" src="****MASKED URL****"></a>

The only difference between the properties of the search button when it is showing or hiding the advanced search is the img src:

When advanced search is hidden the IMG src ends with "/Styles/_Images/advanced_button.jpg", when advanced search is visible, the IMG src ends with "/Styles/_Images/basic_button.png"

When I open the page, sometimes the Advanced search options are showing, sometimes they aren't. The value that I want to search on appears in the Advanced section, so for my script to work I have added an IF statement.

<input type="text" value="" maxlength="30" size="30" name="guiSystemID">

The IF statement looks for the fields that I need to enter data into, and if the field does not exist then that would indicate that the Advanced options are not visible I need to click on the button to expand the search option.

I created the following IF statement.

     if (!driver.findElement(By.name("guiSystemID")).isDisplayed()) {
         driver.findElement(By.cssSelector("img[alt='Advanced']")).click();
     }

When I run the script and the Advanced search is expanded then the script runs successfully. However, when I run the script and the Advanced search is not expanded, the script fails, advising me that it could not find the object "guiSystemID". This is frustrating because if it can't find it then I want the script to continue, entering into the True path of the IF statement.

Has anyone got any suggestions about how else I could assess if the field is appearing without having the script fail because it can't find the field.

Thanks in advance

Simon

3 Answers 3

27

I might be late in answering this, but it might help someone else looking for the same.

I recently faced a similar problem while working with isDisplayed(). My code was something like this

if(driver.findElement(By.xpath(noRecordId)).isDisplayed() )                                                                                                         
{         
  /**Do this*/     
}    
else    
{     
  /**Do this*/    
}

This code works pretty well when the element that isDisplayed is trying to find is present. But when the element is absent, it continues looking for that and hence throws an exception "NosuchElementFound". So there was no way that I could test the else part.

I figured out a way to work with this(Surround the {if, else} with try and catch block, say something like this.

public void deleteSubVar() throws Exception  
{         
  try   
  {    
    if(driver.findElement(By.xpath(noRecordId)).isDisplayed() )     
    {      
      /**when the element is found do this*/     
    }    
  }      
  catch(Exception e)     
  {       
   /**include the else part here*/     
  }       
}         

Hope this helps :)

0
6

I've had mixed results with .isDisplayed() in the past. Since there are various methods to hide an element on the DOM, I think it boils down to a flexibility issue with isDisplayed(). I tend to come up with my own solutions to this. I'll share a couple things I do, then make a recommendation for your scenario.

Unless I have something very specific, I tend to use a wrapper method that performs a number of checks for visibility. Here's the concept, I'll leave the actual implementation approach to you. For general examples here, just assume "locator" is your chosen method of location (CSS, XPath, Name, ID, etc).

The first, and easiest check to make is to see if the element is even present on the DOM. If it's not present, it certainly isn't visible.

boolean isPresent = driver.findElements(locator).size() > 0;

Then, if that returns true, I'll check the dimensions of the element:

Dimension d = driver.findElement(locator).getSize();
boolean isVisible = (d.getHeight() > 0 && d.getWidth() > 0);

Now, dimensions, at times, can return a false positive if the element does in fact have height and width greater than zero, but, for example, another element covers the target element, making it appear hidden on the page (at least, I've encountered this a few times in the past). So, as a final check (if the dimension check returns true), I look at the style attribute of the element (if one has been defined) and set the value of a boolean accordingly:

String elementStyle = driver.findElement(locator).getAttribute("style");
boolean isVisible = !(elementStyle.equals("display: none;") || elementStyle.equals("visibility: hidden;"));

These work for a majority of element visibility scenarios I encounter, but there are times where your front end dev does something different that needs to be handled on it's own.

An easy scenario is when there's a CSS class that defines element visibility. It could be named anything, so let's assume "hidden" to be what we need to look for. In this case, a simple check of the 'class' attribute should yield suitable results (if any of the above approaches fail to do so):

boolean isHidden = driver.findElement(locator).getAttribute("class").contains("hidden");

Now, for your particular situation, based on the information you've given above, I'd recommend setting a boolean value based on evaluation of the "src" attribute. This would be a similar approach to the CSS class check just above, but used in a slightly different context, since we know exactly what attribute changes between the two states. Note that this would only work in this fashion if there are two states of the element (Advanced and Basic, as you've noted). If there are more states, I'd look into setting an enum value or something of the like. So, assuming the element represents either Advanced or Basic:

boolean isAdvanced = driver.findElement(locator).getAttribute("src").contains("advanced_button.jpg");

From any of these approaches, once you have your boolean value, you can begin your if/then logic accordingly.

My apologies for being long winded with this, but hopefully it helps get you on the right path.

2
  • 2
    Whilst I'll agree with you on the "oddities" that isDisplayed can bring, you are actually duplicating exactly what it is already doing. Selenium is open source after all, the JS code used lives here. This does the exact same thing as you are doing (i.e checking height & width, display styles etc). You can also check out the WebDriver spec where it details these steps. Personally, it comes down to there not being a "one size fits all" way of checking it.
    – Arran
    Jul 25, 2014 at 9:42
  • This worked for me. There seems to be an issue with Selenium regarding returning false when an input of type checkbox is clearly displayed. Using this method works. Jan 24, 2019 at 21:16
1

Use of Try Catch defies the very purpose of isdisplayed() used as If condition, one can write below code without using "if"

try{
driver.findElement(By.xpath(noRecordId)).isDisplayed();
//Put then statements here
   }
Catch(Exception e)
{//put else statement here.}

Not the answer you're looking for? Browse other questions tagged or ask your own question.