问题
I'm trying to get a text from a html page which is into a hidden span.
<span class="hide"> Nike </span>
I've tried something like this:
WebElement element = driver.findElement(By.cssSelector(".product-page.clearfix > .hide > span"));
String content = (String)((JavascriptExecutor)driver).executeScript("arguments[0].innerHTML;", element);
product.setBrand(content)
I've tried also with "return arguments[0].innerHTML;
" and with "element.getText()
"
I understood that I can use pure javascript, but this is a simple example, I need to use WebDriver and Java code for more complicated pages.
java.lang.ClassCastException: package.driver.DhlWebDriver cannot be cast to org.openqa.selenium.JavascriptExecutor
回答1:
You just need to get a proper attribute like following:element.GetAttribute("textContent");
Should work well.
I guess getAttribute for JAVA - I work in C#.
回答2:
Try this it will work
WebElement element = driver.findElement(By.cssSelector(".product-page.clearfix > .hide > span"));
String content = (String) ((JavascriptExecutor) driver).executeScript("return arguments[0].innerHTML", element);
System.out.println(content);
I'm using return arguments[0].innerHTML
回答3:
I recommand to use:
JavascriptExecutor js = (JavascriptExecutor)element;
String content=(String) js.executeScript("return document.getElementsByClassName('hide').value;");
System.out.println(content);
来源:https://stackoverflow.com/questions/33498234/getting-a-hidden-text-from-a-html-in-java-using-selenium-and-webdriver