在某度搜索java html解析,搜到比较多的是htmlparser,这个包很长时间没有更新、没有文档,网上的一些使用总结都比较老。
再找时就发现了jsoup,看了一下文档,和python的beautifulsoup包的使用方法比较接近,使用比htmlparser更简单。该软件包使用MIT协议,可免费用于任何用途。
主页:https://jsoup.org/
简单使用如下:
Example
下载html页面:
Document doc = Jsoup.connect("http://example.com/").get();
String title = doc.title();
获取页面元素
Element content = doc.getElementById("content");
Elements links = content.getElementsByTag("a");
for (Element link : links) {
String linkHref = link.attr("href");
String linkText = link.text();
}
设置请求的http头
Document doc = Jsoup.connect("http://example.com")
.data("query", "Java")
.userAgent("Mozilla")
.cookie("auth", "token")
.timeout(3000)
.post();
提取属性、文本、html元素
String html = "<p>An <a href='http://example.com/'><b>example</b></a> link.</p>";
Document doc = Jsoup.parse(html);
Element link = doc.select("a").first();
String text = doc.body().text(); // "An example link"
String linkHref = link.attr("href"); // "http://example.com/"
String linkText = link.text(); // "example""
String linkOuterH = link.outerHtml();
// "<a href="http://example.com"><b>example</b></a>"
String linkInnerH = link.html(); // "<b>example</b>"