Navegar por un documento HTML
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.
Navegación HTML
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:
Property | Description |
---|---|
FirstChild | Accessing this attribute of an element must return a reference to the first child node. |
LastChild | Accessing this attribute of an element must return a reference to the last child node |
NextSibling | Accessing this attribute of an element must return a reference to the sibling node of that element which most immediately follows that element. |
PreviousSibling | Accessing this attribute of an element must return a reference to the sibling node of that element which most immediately precedes that element. |
ChildNodes | Returns 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// Navigate the HTML DOM using Java
2
3// Prepare HTML code
4String html_code = "<span>Hello,</span> <span>World!</span>";
5
6// Initialize a document from the prepared code
7HTMLDocument document = new HTMLDocument(html_code, ".");
8
9// Get the reference to the first child (first <span>) of the document body
10Element element = document.getBody().getFirstElementChild();
11System.out.println(element.getTextContent());
12// @output: Hello,
13
14// Get the reference to the second <span> element
15element = element.getNextElementSibling();
16System.out.println(element.getTextContent());
17// @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:
1// Create custom NodeFilter to accept only image elements in Java
2
3public static class OnlyImageFilter extends NodeFilter {
4 @Override
5 public short acceptNode(Node n) {
6 // The current filter skips all elements, except IMG elements
7 return "img".equals(n.getLocalName())
8 ? FILTER_ACCEPT
9 : FILTER_SKIP;
10 }
11}
Una vez que implementa un filtro, puede usar la navegación HTML como sigue:
1// Filter HTML elements using TreeWalker and custom NodeFilter in Aspose.HTML for Java
2
3// Prepare HTML code
4String code = " < p > Hello, </p >\n" +
5 " <img src = 'image1.png' >\n" +
6 " <img src = 'image2.png' >\n" +
7 " <p > World ! </p >\n";
8
9// Initialize a document based on the prepared code
10HTMLDocument document = new HTMLDocument(code, ".");
11
12// To start HTML navigation, we need to create an instance of TreeWalker
13// 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
14ITreeWalker iterator = document.createTreeWalker(document, NodeFilter.SHOW_ALL, new NodeFilterUsageExample.OnlyImageFilter());
15// Use
16while (iterator.nextNode() != null) {
17 // Since we are using our own filter, the current node will always be an instance of the HTMLImageElement
18 // So, we don't need the additional validations here
19 HTMLImageElement image = (HTMLImageElement) iterator.getCurrentNode();
20
21 System.out.println(image.getSrc());
22 // @output: image1.png
23 // @output: image2.png
24}
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// Select HTML elements using XPath expression in Aspose.HTML for Java
2
3// Prepare HTML code
4String code = "< div class='happy' >\n" +
5 " <div >\n" +
6 " <span > Hello! </span >\n" +
7 " </div >\n" +
8 " </div >\n" +
9 " <p class='happy' >\n" +
10 " <span > World! </span >\n" +
11 " </p >\n";
12
13// Initialize a document based on the prepared code
14HTMLDocument document = new HTMLDocument(code, ".");
15
16// Here, we evaluate the XPath expression where we select all child <span> elements from elements whose 'class' attribute equals to 'happy'
17IXPathResult result = document.evaluate("//*[@class='happy']//span",
18 document,
19 null,
20 XPathResultType.Any,
21 null
22);
23
24// Iterate over the resulted nodes
25for (Node node; (node = result.iterateNext()) != null; ) {
26 System.out.println(node.getTextContent());
27 // @output: Hello!
28 // @output: World!
29}
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// Select HTML elements using CSS selector querySelectorAll method in Aspose.HTML for Java
2
3// Prepare HTML code
4String code = "< div class='happy' >\n" +
5 " <div >\n" +
6 " <span > Hello, </span >\n" +
7 " </div >\n" +
8 " </div >\n" +
9 " <p class='happy' >\n" +
10 " <span > World ! </span >\n" +
11 " </p >\n";
12
13// Initialize a document based on the prepared code
14HTMLDocument document = new HTMLDocument(code, ".");
15
16// Here, we create a CSS Selector that extracts all elements whose 'class' attribute equals to 'happy' and their child SPAN elements
17NodeList elements = document.querySelectorAll(".happy span");
18
19// Iterate over the resulted list of elements
20elements.forEach(element -> {
21 System.out.println(((HTMLElement) element).getInnerHTML());
22 // @output: Hello,
23 // @output: World!
24});
Aspose.HTML ofrece Extractor de palabras clave, una herramienta basada en IA para extraer palabras clave de páginas web, texto sin formato o archivos. Esta aplicación le ayuda a identificar rápidamente temas y tendencias clave para la optimización de sitios web, el análisis de la competencia o el resumen de documentos de gran tamaño. Basta con pegar el texto o la URL, seleccionar la configuración y hacer clic en “Extraer” para obtener palabras clave precisas y significativas en cuestión de segundos. Ideal para mejorar la visibilidad en los motores de búsqueda, la orientación de contenidos y la toma de decisiones basada en datos.