Навигация по HTML документу – примеры Java

В этой статье вы узнаете, как перемещаться по HTML-документу и выполнять детальную проверку его элементов с помощью API Aspose.HTML for Java. Вы можете легко создать собственное приложение для анализа, сбора или извлечения информации из HTML-документов, поскольку наш API предоставляет мощный набор инструментов для навигации по документу с помощью CSS Selector, XPath Query или пользовательских фильтров.

HTML-навигация

Существует множество способов создания HTML-навигации. В следующем списке показан самый простой способ доступа ко всем элементам DOM используя класс 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.

Используя упомянутые свойства, вы можете перемещаться по HTML-документу следующим образом:

 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!

Для более сложных сценариев, когда вам нужно найти узел по определенному шаблону (например, получить список заголовков, ссылок и т. д.), вы можете использовать специализированный TreeWalker или NodeIterator объект с собственной реализацией Filter.

В следующем примере показано, как реализовать собственный NodeFilter для пропуска всех элементов, кроме изображений:

 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}

После реализации фильтра вы можете использовать HTML-навигацию следующим образом:

 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

Альтернативой HTML-навигации является XML Path Language. Синтаксис выражений XPath довольно прост и, что более важно, его легко читать и поддерживать.

В следующем примере показано, как использовать запросы XPath в Java API Aspose.HTML:

 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}

CSS-селектор

Наряду с HTML Navigation и XPath вы ​​можете использовать CSS Selector API, который также поддерживается нашей библиотекой. Этот API предназначен для создания шаблона поиска для сопоставления элементов в дереве документа на основе синтаксиса 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 предлагает Извлечение ключевых слов – инструмент для извлечения ключевых слов из веб-страниц, обычного текста или файлов, работающий на основе искусственного интеллекта. Это приложение поможет вам быстро определить ключевые темы и тенденции для оптимизации сайта, анализа конкурентов или обобщения больших документов. Просто вставьте текст или URL-адрес, выберите настройки и нажмите “Extract”, чтобы получить точные, значимые ключевые слова за считанные секунды. Идеально подходит для улучшения видимости в поисковых системах, таргетирования контента и принятия решений на основе данных.

Текст “Извлечение ключевых слов”

Close
Loading

Analyzing your prompt, please hold on...

An error occurred while retrieving the results. Please refresh the page and try again.

Subscribe to Aspose Product Updates

Get monthly newsletters & offers directly delivered to your mailbox.