0

I have an html tag which is not visible on screen (isDisplayed returns false) but i want to get the value of it. For eg:

<div class="qgwy">Gift No.3726</div>

I want to extract the value "Gift No.3726". I tried this code and it prints nothing:

WebElement gwy = driver.findElement(By.cssSelector(".qgwy"));
System.out.println(gwy.getText());

After careful comparisons, I realized that, the getText() method only works for elements' tag which are visible (or not hidden) on screen. So, I was wondering if it's possible to extract that data without asking my developers to modify the code.

Unihedron
  • 10,902
  • 13
  • 62
  • 72
Zakir Sayed
  • 200
  • 2
  • 12

1 Answers1

1

Yep, its possible:

Q: Why is it not possible to interact with hidden elements? A: Since a user cannot read text in a hidden element, WebDriver will not allow access to it as well.

However, it is possible to use Javascript execution abilities to call getText directly from the element:

WebElement element = ...;
((JavascriptExecutor) driver).executeScript("return arguments[0].getText();", element);

from Selenium FAQ: https://code.google.com/p/selenium/wiki/FrequentlyAskedQuestions#Q:_Why_is_it_not_possible_to_interact_with_hidden_elements?

Alex Chernyshev
  • 1,719
  • 9
  • 11
  • Thanks Alex for the reply. Can you help me to point out where I am doing it wrong as I am getting exception: "arguments[0].getText is not a function" WebElement elm = browser.findElement(By.cssSelector(".desktopmode")); String hiddenvalue = (String) ((JavascriptExecutor) browser).executeScript("return arguments[0].getText();", elm); System.out.println(hiddenvalue); – Zakir Sayed Aug 03 '14 at 15:49
  • Seems like element was not found. Check that elm variable is not null – Alex Chernyshev Aug 03 '14 at 16:01
  • It's not null. Tried with other visible object where it prints the value of the html tag using webdriver getText() method. However, javascriptexecutor always complains by exception (getText() is not a function). – Zakir Sayed Aug 03 '14 at 22:47
  • replace getText() with .innerHTML http://stackoverflow.com/questions/10370204/how-can-get-the-text-of-a-div-tag-using-only-javascript-no-jquery – Alex Chernyshev Aug 03 '14 at 23:59
  • Yes, innerHTML works. Thanks Alex for helping out till the end. – Zakir Sayed Aug 04 '14 at 03:54