3

I'm using Selenium and C# to test a widget that is implemented across multiple websites however on a few of these websites there is an additional drop down. I'd rather not just ignore this additional drop down but I am trying to incorporate an if statement into my test to handle it.

    [Then(@"I Input an Option If Available")]
    public void ThenIInputAnOptionIfAvailable()
    {
        var option = CurrentBrowserFindElement(By.Name("option1"));
    }

I can't get past the point of finding the element - I am hoping someone here can teach me how to handle conditions similar to these with C# and Selenium.

3

The easiest way to implement what you need is to create a boolean method that checks if element exist (visible) on the page:

  public static boolean CheckIfElementVisible(By by){
    var _wait = new WebDriverWait(YourWebDriverInstance, TimeSpan.FromSeconds(30));
    try
    {
        _wait.Until(ExpectedConditions.ElementIsVisible(by));
        System.Diagnostics.Debug.Write("Element" + " " + @by + " " + "is visible");
    }
    catch (Exception e)
    {
        System.Diagnostics.Debug.Write("Element" + " " + @by + " " +  "is not found |" + " " + e.Message);
    }
   }
  }

Explanation of the piece of code:

by - your element identifier (ID, CSS, Xpath and etc.)

TimeSpan.FromSeconds(30) - time to wait for an element. I usually set to 30 seconds

try / catch block - this way your test won't fail if element is not found.

This will either return true if element exist and then you can interact with it, or either returns false and you can skip to the next step. Hope this helps.

1

There is much easier way than the accepted answer: find_elements() returns a list of elements, empty if none are present. No try-catch, no timeout, no wait, no hassle.

  • As far as I understood he needs to locate a single drop down on the page, and interact with it if it's there. – Tired Of Testing Oct 12 '17 at 13:28
  • Correct. Checking if returned list is empty (if element is not present) is IMNSHO easier that try/catch you used. – Peter M. Oct 12 '17 at 14:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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