I was wondering if there's any solution for getting text of a web element if it's present on screen?

Application which I'm automating right now is sometimes displaying unexpected error alert with error code. I want to create a listener that gets the text of the error alert if it's displayed and prints it into console.

I'm using TestNG framework with Selenium WebDriver and Java.

I tried to find any solution on the web but none answered my problem. Only found a way to take screenshot on test fail which is not really solution to my problem.

1 Answers

0
Kajal Kundu On

Check the length count of the WebElements.If length count more than 0 then fetch the text of the element.Let me know how it goes. check the text if returns null then try innerHTML property.

WebDriverWait wait=new WebDriverWait(driver, 30);
        List<WebElement> errelements =wait.until(ExpectedConditions.presenceOfAllElementsLocatedBy(By.xpath("xpath of locator")));
        if(errelements.size()>0)
        {
         System.out.println(errelements.get(0).getText()); 
         System.out.println(errelements.get(0).getAttribute("innerHTML"));  
        }