Vizag
Vizag

Reputation: 395

Unable to locate css element through IfElse statement

I am opening a mail in an inbox and grab a url from the open mail content, which I want to use for further actions. The url to be used could be only one of the above css elements( from different mails)

if (getDriver().findElement(By.css("body > p:nth-child(5)")) != null) {
    String URL = getDriver().findElement(By.css("body > p:nth-   child(5)")).getText(); 
} else {
    String mailBody = getDriver().findElement(By.css("body > p:nth-child(2)")).getText();
    String[] temp = mailBody.split("\n");
    String URL = temp[2];
    System.out.println(URL);     
}

String resetLink = URL;
System.out.println(resetLink);
getDriver().get(resetLink);

Here for me the script is failing to locate the element with below error (it is in one way is correct because the required url can be grabbed by the 'else' part of the code.

NoSuchWebElementException: Unable to locate element: By[method = css, selector = "body > p:nth-child(5)"]

I was expecting to first run the 'if' statement to check for Url , if it is not there, then I want the 'else' statement to be run and then grab the Url from the mail body.

Please help me by pointing where am I making mistake. Thank you for any of your suggestions. regards,

Upvotes: 0

Views: 53

Answers (2)

Marcel
Marcel

Reputation: 1463

Find element will throw a NoSuchWebElementException if it doesn't find anything, it will not return null. You can use a try catch

WebElement element;
String URL;

try {
    element = getDriver().findElement(By.css("body > p:nth-child(5)"));
    URL = element.getText();
} catch (Exception e) {
    String mailBody = getDriver().findElement(By.css("body > p:nth-child(2)")).getText();
    String[] temp = mailBody.split("\n");
    URL = temp[2];
    System.out.println(URL); 
}

Upvotes: 1

Admit
Admit

Reputation: 4987

If you would prefer if/else approach instead of exception being thrown - here is a suggestion from javaDoc:

findElement should not be used to look for non-present elements, use findElements(By) and assert zero length response instead.

Upvotes: 1

Related Questions