Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java selenium grabbing entire html contents of the element

I was wondering if there was a way to get the entire html code between two tags of an element, along with the element tag then store it in a string.

Lets say I use the following to create a list of web elements, then fill the list with all the web elements.

List<WebElement> element = driver.findElements(By.xpath("//*"));
//Some for loop after this to access each value

If I use the following to get the 3rd web element, it prints only the tags name, as it should:

System.out.println(element.get(3).getTagName()); 

so it prints the paragraph element "p" or "input" for example if it is the 3rd web element stored

But I was wondering if its possible to get the entire html code line for the web element and print it rather then only the tag name "p" for example?

e.g.

<p> some text </p>

Is there some way to accomplish this?

like image 868
Xians Wu Avatar asked Mar 30 '17 21:03

Xians Wu


People also ask

How do I get HTML from WebElement?

We can get the html code of a webelement with the help of Selenium webdriver. We can obtain the innerHTML attribute to get the HTML content of the web element. The innerHTML is an attribute of a webelement which is equal to the content that is present between the starting and ending tag.

How do I get HTML text in Selenium?

To get the HTML source of a WebElement in Selenium WebDriver, we can use the get_attribute method of the Selenium Python WebDriver. First, we grab the HTML WebElement using driver element locator methods like (find_element_by_xpath or find_element_by_css_selector).

How do I getText to full page in Selenium?

To get the text of the visible on the page we can use the method findElement(By. tagname()) method to get hold of . Next can then use the getText() method to extract text from the body tag.


1 Answers

You can read outerHTML attribute to get the entire element.

element.getAttribute("outerHTML");

Or in your case:

System.out.println(element.get(3).getAttribute("outerHTML")); 

Hope it helps!

like image 200
Aaron N. Brock Avatar answered Oct 15 '22 10:10

Aaron N. Brock