I have a
.
I try to write a test that myDiv has 0 text in it. With WebDriver it is:
<It sounds like you are using HTMLUnitDriver. In that case you would need to enable the JavaScript code like below.
HtmlUnitDriver driver = new HtmlUnitDriver();
driver.setJavascriptEnabled(true);
Check out the documentation here.
You can use getText() even if it doesn't have any content. That should not be the issue.
From your answer, the issue seems to be that you didn’t instantiate the FirefoxDriver.
Selenium WebDriver will only interact with visible elements, and therefore the text of an invisible element will always be returned as an empty string.
Try this
WebDriver driver = new YourBrowserdirver(); //FirefoxDriver or ChromeDriver etc..
String Text = driver.findElement(By.id("myDiv")).getText();
System.out.println("The text present in myDiv = "+Text);
You can also verify the text in the div by:
$browser.is_element_present("//div[@name='myDiv']/.[text()='0']")
You can try using the jsoup library for parsing HTML.
First just load the page content (driver.getPageSource()) to the jsoup document object and use the richness of methods of that excellent library (kudos to the author).
Example:
String pageSource = driver.getPageSource();
Document doc = Jsoup.parse(pageSource);
Elements requestsListRecords = doc.getElementsByTag("table").get(2).getElementsByTag("tr");
I had the same problem; a little digging brought me to this:
https://groups.google.com/forum/#!msg/webdriver/fRb_1QOr3wg/wzUsW3Ll6bgJ
HTMLUnitDriver (and apparently FirefoxDriver) will return empty strings when you try to call WebElement#getText() on elements whose CSS property 'display' is set to 'none'.
Here is my solution:
public void assertContainsText(final By by, final String value) {
browser.waitTillElementPresent(by);
Boolean result = new WebDriverWait(getWebDriver(),Browser.DEFAULT_WAIT_TIMEOUT_SECONDS).until(new ExpectedCondition<Boolean>() {
@Override
public Boolean apply(WebDriver arg0) {
WebElement elem = arg0.findElement(by);
String text = "";
if (elem.isDisplayed()) {
text = elem.getText();
} else {
//have to use JavaScript because HtmlUnit will return empty string for a hidden element's text
text = (String) executeScript("return arguments[0].innerHTML", elem);
text = text.replace("<BR></BR>", "\n"); //scary
}
return text.contains(value);
}
});
Assert.assertTrue(by.toString() + " contains value ["+value+"]", result);
}
Yes, it's ugly as sin. And note the text.replace("<BR></BR>") - this is because HTML tags aren't escaped when you pull out the raw data. The WebDriver will nicely 'unescape' this if you call #getText() on the element.
I've now put in a request to our IT guys to install X-Windows on our CI servers so we can run the FirefoxDriver. We've had nothing but trouble from the HTMLUnitDriver, and it's incredibly slow to boot.