AutomaticStatic
AutomaticStatic

Reputation: 1729

Selenium: Handling exceptions for element that may not be present

I have a handful of pages where I want to look for an element, and if it is present, get the text. But I've run into a bit of a conundrum with respect to exception handling.

I can use WebDriverWait:

wait.until(EC.presence_of_element_located((By.XPATH, '//div[@class="className"]')))

But if this throws an exception, I technically have no way of knowing whether it occurred because the element is in fact not present on the page, or because of something else (e.g. I didn't wait long enough or there's some other error in the code).

In my particular case I've been able to deal with this so far by using the presence of some other elements on the page to infer whether the one I'm looking for will be present. However, I am bound to run into some pages where I can't use other elements as proxies.

Is there any way for me to distinguish between an exception caused by the element actually not being in the page source versus some other reason?

Upvotes: 0

Views: 938

Answers (1)

Zach
Zach

Reputation: 1006

You should specify the Exception you want to catch and then do something in the catchblock, refer to the Java Doc here to give you more insight on exceptions

http://selenium.googlecode.com/git/docs/api/java/index.html

   public void aMethod() {
       try {
        //do someting
               } catch( Exception e ) {
        textLog( "Element not present -------" );
       detailedText( e );
    }

}

Upvotes: 1

Related Questions