0

Facing issue to read content after clicking an element in Selenium. I have tried with below code:

if(webElement2.isDisplayed()) {
            webElement.explicitWaitToClickElement(4,webElement);
            webElement2.click();
}

String tagContent = (String) ((JavascriptExecutor) 
BrowserUtilities.getDriver()).executeScript("return arguments[0].innerText;", webElement2);
1
  • 2
    Please update your question with the error you're seeing.
    – anonygoose
    Feb 5, 2019 at 13:06

3 Answers 3

0

Your code does the following:

  • If webElement2 is displayed, wait for some other element, webElement, to be visible and click on webElement2;
  • Grab the text on webElement2.

It can be failing because webElement2 is never displayed.

Probably, what you want is:

  • If webElement2 is not displayed, click on webElement (not webElement2);
  • Wait for webElement2 to be visible;
  • Grab the text from webElement2.

OBS: I will edit this answer based on @anonygoose's request.

0

Try to get the attributes of the webElement2 which you are referring at your code.

String aa = webElement2.getAttribute("text").toString();
0

The code you have provided looks correct, but it might not be working as expected because the element you are trying to click might not be visible or enabled when you try to execute the JavascriptExecutor code to retrieve the inner text.

Here's an alternate approach that you can try to get the content of a clickable element in Selenium:

1 Click the element using click() method:

webElement2.click();

2 Retrieve the inner text of the element using getText() method:

String tagContent = webElement2.getText();

By clicking the element first, you ensure that it is visible and enabled before trying to retrieve the inner text.

If you still face issues with this approach, you can try to add a small wait before retrieving the inner text to allow the element to fully load and render on the page. You can use the WebDriverWait class for this purpose, like below:

WebElement webElement2 = driver.findElement(By.xpath("//yourXpath"));
webElement2.click();

WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//yourXpath")));

String tagContent = webElement2.getText();

The visibilityOfElementLocated method waits for the element to become visible on the page before continuing.

I hope this helps you to get the content of a clickable element in Selenium.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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