简体   繁体   中英

Get text of WebElement which contains html tags

How can I get the Inner HTML of a WebElement with Selenium?

This is what I've tried so far:

WebElement divData=driver.findElement(By.id("data"));  
divData.getText();  //returns empty   
OR  
divData.getAttribute("innerHTML"); //returns empty  
OR  
String script="return arguments[0].innerHTML";  
String result=(String) ((JavascriptExecutor)driver).executeScript(script,divData);

System.out.println(""+result); //empty

as I see from the comment {quote}


"This is school"

{quote}

Representing the above in a tree view: HTML的树状视图

So basic webdriver method WebElement.getText() should work for any properly located element which contains the text.

So there 2 possbilities to find the text of webelement:

  • I) try get text from all sublements (childs) related to the div above:

     List<WebElement> childsOfDiv =driver.findElements(By.cssSelector(#data>*)); for(WebElement iter: childsOfDiv){ System.out.println(iter.getText()); } 
  • II) get elements' text by js method involving javascriptexecutor Initial step is to find locators of child elements related to div:

     String child1CSS="#data>b"; String child2CSS="#data>br"; public String getTextInvolvingJs(String cssLocator) { JavascriptExecutor js = (JavascriptExecutor) driver; StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("var x = $(\\""+cssLocator+"\\");"); stringBuilder.append("return x.text().toString();") ; String res= (String) js.executeScript(stringBuilder.toString()); return res; } String foundText1= getTextInvolvingJs(child1CSS); String foundText2= getTextInvolvingJs(child2CSS); 

Hope this works for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM