Навигация по HTML документу – примеры Java
В этой статье вы узнаете, как перемещаться по HTML-документу и выполнять детальную проверку его элементов с помощью API Aspose.HTML for Java. Вы можете легко создать собственное приложение для анализа, сбора или извлечения информации из HTML-документов, поскольку наш API предоставляет мощный набор инструментов для навигации по документу с помощью CSS Selector, XPath Query или пользовательских фильтров.
HTML-навигация
Существует множество способов создания HTML-навигации. В следующем списке показан самый простой способ доступа ко всем элементам DOM используя класс 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. |
Используя упомянутые свойства, вы можете перемещаться по HTML-документу следующим образом:
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!
Для более сложных сценариев, когда вам нужно найти узел по определенному шаблону (например, получить список заголовков, ссылок и т. д.), вы можете использовать специализированный TreeWalker или NodeIterator объект с собственной реализацией Filter.
В следующем примере показано, как реализовать собственный NodeFilter для пропуска всех элементов, кроме изображений:
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}
После реализации фильтра вы можете использовать HTML-навигацию следующим образом:
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
Альтернативой HTML-навигации является XML Path Language. Синтаксис выражений XPath довольно прост и, что более важно, его легко читать и поддерживать.
В следующем примере показано, как использовать запросы XPath в Java API Aspose.HTML:
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}
CSS-селектор
Наряду с HTML Navigation и XPath вы можете использовать CSS Selector API, который также поддерживается нашей библиотекой. Этот API предназначен для создания шаблона поиска для сопоставления элементов в дереве документа на основе синтаксиса 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});