Collections:
Dump Elements with By.xpath() in Java
How to dump all HTML elements of a Web page with WebDriver in Java?
✍: FYIcenter.com
If you want to dump all HTML elements of a Web page with WebDriver,
you can search child element recursively using the By.xpath() method.
Here is an example program that dumps all HTML elements of the loaded Web page.
// DumpElements.java
// Copyright (c) FYIcenter.com
import org.openqa.selenium.*;
public class DumpElements {
public static void main(String[] args) {
WebDriver driver = WebDriverLoader.load(args[0]);
driver.get("http://sqa.fyicenter.com");
WebElement html = driver.findElement(By.tagName("html"));
printTag(html,"");
driver.quit();
}
public static void printTag(WebElement tag, String space) {
java.util.List<WebElement> list = tag.findElements(By.xpath("./*"));
if (list==null) {
System.out.println(space+"<"+tag.getTagName()+"/>");
} else {
System.out.println(space+"<"+tag.getTagName()+">");
for (WebElement child: list) {
printTag(child,space+" ");
}
System.out.println(space+"</"+tag.getTagName()+">");
}
}
}
Compile and run the program, you will see that all elements of the Web page are dumped in the output:
C:\fyicenter> javac -classpath \
.;\fyicenter\selenium\java\client-combined-3.141.59.jar \
DumpElements.java
C:\fyicenter> java -classpath \
.;\fyicenter\selenium\java\client-combined-3.141.59.jar;\
\fyicenter\selenium\java\libs\guava-25.0-jre.jar;\
\fyicenter\selenium\java\libs\okhttp-3.11.0.jar;\
\fyicenter\selenium\java\libs\okio-1.14.0.jar;\
\fyicenter\selenium\java\libs\commons-exec-1.3.jar \
DumpElements Chrome
<html>
<head>
<meta>
</meta>
<meta>
</meta>
...
<link>
</link>
<title>
</title>
<script>
</script>
<script>
</script>
...
<link>
</link>
<script>
</script>
<link>
</link>
</head>
<body>
<div>
<div>
<p>
</p>
<p>
<a>
</a>
</p>
<p>
<a>
</a>
</p>
<p>
...
</div>
</div>
</body>
</html>
The output looks good. But element attributes are not included in the output. See the next tutorial on how the dump HTML attributes.
⇒ Dump Element Attributes with JavascriptExecutor in Java
⇐ JavascriptExecutor to Run JavaScript in Java
2020-01-04, ∼2781🔥, 0💬
Popular Posts:
How to use HTTP protocol to post an XML message to a server? You can follow this tutorial to post an...
How to valid IP addresses? In order to help your programming or testing tasks, FYIcenter.com has des...
How to update hidden input value field value with WebDriver in Python? Normally, a hidden input valu...
Where to find tutorials on Apache JMeter test tool? I want to know how to use Apache JMeter. Here is...
How to set Content-Type to application/json? The server requires the Content-Type to be application/...