Navegación HTML – Ejemplos de Java

En este artículo, aprenderá cómo navegar a través de un documento HTML y realizar una inspección detallada de sus elementos utilizando Aspose.HTML for Java API. Puede crear fácilmente su propia aplicación para analizar, recopilar o extraer información de los documentos HTML, ya que nuestra API proporciona un poderoso conjunto de herramientas para navegar por el documento utilizando CSS Selector, XPath Consuly o Filtros personalizados.

Hay muchas maneras que se pueden usar para hacer navegación HTML. La siguiente lista de la lista muestra la forma más sencilla de acceder a todos los elementos DOM utilizando la clase Node:

PropertyDescription
FirstChildAccessing this attribute of an element must return a reference to the first child node.
LastChildAccessing this attribute of an element must return a reference to the last child node
NextSiblingAccessing this attribute of an element must return a reference to the sibling node of that element which most immediately follows that element.
PreviousSiblingAccessing this attribute of an element must return a reference to the sibling node of that element which most immediately precedes that element.
ChildNodesReturns a list that contains all children of that element.

Usando las propiedades mencionadas, puede navegar a través de un documento HTML como sigue:

 1// Prepare HTML code
 2String html_code = "<span>Hello,</span> <span>World!</span>";
 3
 4// Initialize a document from the prepared code
 5HTMLDocument document = new HTMLDocument(html_code, ".");
 6
 7// Get the reference to the first child (first <span>) of the document body
 8Element element = document.getBody().getFirstElementChild();
 9System.out.println(element.getTextContent());
10// output: Hello,
11
12// Get the reference to the second <span> element
13element = element.getNextElementSibling();
14System.out.println(element.getTextContent());
15// output: World!

Para los escenarios más complicados, cuando necesita encontrar un nodo basado en un patrón específico (por ejemplo, obtener la lista de encabezados, enlaces, etc.), puede usar un TreeWalker o NodeIterator objeto con una implementación personalizada Filter.

El siguiente ejemplo muestra cómo implementar su propio NodeFilter para omitir todos los elementos excepto las imágenes:

1public static class OnlyImageFilter extends NodeFilter {
2@Override
3    public short acceptNode(Node n) {
4        // The current filter skips all elements, except IMG elements.
5        return "img".equals(n.getLocalName())
6                ? FILTER_ACCEPT
7                : FILTER_SKIP;
8    }
9}
Example_OnlyImageFilter hosted with ❤ by GitHub

Una vez que implementa un filtro, puede usar la navegación HTML como sigue:

 1// Prepare HTML code
 2String code = "    < p > Hello, </p >\n" +
 3        "    <img src = 'image1.png' >\n" +
 4        "    <img src = 'image2.png' >\n" +
 5        "    <p > World ! </p >\n";
 6
 7// Initialize a document based on the prepared code
 8HTMLDocument document = new HTMLDocument(code, ".");
 9
10// To start HTML navigation, we need to create an instance of TreeWalker
11// The specified parameters mean that it starts walking from the root of the document, iterating all nodes, and using our custom implementation of the filter
12ITreeWalker iterator = document.createTreeWalker(document, NodeFilter.SHOW_ALL, new HtmlNavigationTests.OnlyImageFilter());
13// Use
14while (iterator.nextNode() != null) {
15    // Since we are using our own filter, the current node will always be an instance of the HTMLImageElement
16    // So, we don't need the additional validations here
17    HTMLImageElement image = (HTMLImageElement) iterator.getCurrentNode();
18
19    System.out.println(image.getSrc());
20    // output: image1.png
21    // output: image2.png
22}

XPath

La alternativa a la navegación HTML es XML Path Language. La sintaxis de las expresiones XPath es bastante simple y lo que es más importante, es fácil de leer y apoyar.

El siguiente ejemplo muestra cómo usar consultas XPATH dentro de la Aspose.HTML for Java API:

 1// Prepare HTML code
 2String code = "< div class='happy' >\n" +
 3        "        <div >\n" +
 4        "            <span > Hello! </span >\n" +
 5        "        </div >\n" +
 6        "    </div >\n" +
 7        "    <p class='happy' >\n" +
 8        "        <span > World! </span >\n" +
 9        "    </p >\n";
10
11// Initialize a document based on the prepared code
12HTMLDocument document = new HTMLDocument(code, ".");
13
14// Here, we evaluate the XPath expression where we select all child <span> elements from elements whose 'class' attribute equals to 'happy'
15IXPathResult result = document.evaluate("//*[@class='happy']//span",
16        document,
17        null,
18        XPathResultType.Any,
19        null
20);
21
22// Iterate over the resulted nodes
23for (Node node; (node = result.iterateNext()) != null; ) {
24    System.out.println(node.getTextContent());
25    // output: Hello!
26    // output: World!
27}

Selector de CSS

Junto con HTML navegación y XPath puede usar CSS Selector API que también es compatible con nuestra biblioteca. Esta API está diseñada para crear un patrón de búsqueda para que coincida con elementos en un árbol de documentos basado en la sintaxis CSS Selectors.

 1// Prepare HTML code
 2String code = "< div class='happy' >\n" +
 3        "        <div >\n" +
 4        "            <span > Hello, </span >\n" +
 5        "        </div >\n" +
 6        "    </div >\n" +
 7        "    <p class='happy' >\n" +
 8        "        <span > World ! </span >\n" +
 9        "    </p >\n";
10
11// Initialize a document based on the prepared code
12HTMLDocument document = new HTMLDocument(code, ".");
13
14// Here, we create a CSS Selector that extracts all elements whose 'class' attribute equals to 'happy' and their child SPAN elements
15NodeList elements = document.querySelectorAll(".happy span");
16
17// Iterate over the resulted list of elements
18elements.forEach(element -> {
19    System.out.println(((HTMLElement) element).getInnerHTML());
20    // output: Hello,
21    // output: World!
22});
Subscribe to Aspose Product Updates

Get monthly newsletters & offers directly delivered to your mailbox.