java解析html标签
时间: 2024-01-12 18:22:15 浏览: 142
基于提供的引用内容,我可以给你介绍两种Java解析HTML标签的方法:
1. 使用Jsoup库进行HTML解析
```java
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
public class HtmlParserExample {
public static void main(String[] args) {
String html = "<html><head><title>Jsoup Example</title></head>"
+ "<body><p>Jsoup is a Java library for HTML parsing.</p></body></html>";
Document doc = Jsoup.parse(html);
Element body = doc.body();
String text = body.text();
System.out.println("Parsed HTML: " + text); }
}
```
2. 使用NekoHTML库进行HTML解析
```java
import org.cyberneko.html.parsers.DOMParser;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
public class HtmlParserExample {
public static void main(String[] args) {
String html = "<html><head><title>NekoHTML Example</title></head>"
+ "<body><p>NekoHTML is a Java library for HTML parsing.</p></body></html>";
DOMParser parser = new DOMParser();
try {
parser.parse(new InputSource(new StringReader(html)));
Document doc = parser.getDocument();
NodeList nodeList = doc.getElementsByTagName("p");
if (nodeList.getLength() > 0) {
String text = nodeList.item(0).getTextContent();
System.out.println("Parsed HTML: " + text);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
阅读全文