最近用到了Java解析Html的一個庫Jsoup, 這兒是官網(wǎng) , 在此分享給大家,有這方面需要的朋友可以試一試。
有三個類需要我們了解,分別是Document,Elements,Element
大至用法有兩步
第一步:加載html,,這兒提供兩種方式,一種是從本地加載,一種是從網(wǎng)上直接加載。
從本地加載:
1
2
String html = "YOU HTML STRING";
Document doc = Jsoup.parse(html);
也可以直接從文件加載
1
2
File input = new File("/tmp/input.html");
Document doc = Jsoup.parse(input, "UTF-8", "http:///");
通過url從網(wǎng)絡(luò)加載
1
2
Document doc = Jsoup.connect("http://en./").get();
String title = doc.title();
上面是通過http的get方法,下可以通過post來獲取
1
2
3
4
5
6
Document doc = Jsoup.connect("http://")
.data("query", "Java")
.userAgent("Safari")
.cookie("auth", "token")
.timeout(3000)
.post();
第二步:定位元素
通過定義的api定位無素
定位body
1
2
3
String html = "<div><p>Lorem ipsum.</p>";
Document doc = Jsoup.parseBodyFragment(html);
Element body = doc.body();
定位標簽
1
2
3
4
5
6
Element content = doc.getElementById("content");
Elements links = content.getElementsByTag("a");
for (Element link : links) {
String linkHref = link.attr("href");
String linkText = link.text();
}
常用的API有
查找API:
1
2
3
4
5
6
getElementById(String id)
getElementsByTag(String tag)
getElementsByClass(String className)
getElementsByAttribute(String key) (and related methods)
兄弟關(guān)系的:siblingElements(), firstElementSibling(), lastElementSibling(); nextElementSibling(), previousElementSibling()
父子關(guān)系的: parent(), children(), child(int index)
值操作API:
1
2
3
4
5
6
7
8
attr(String key) to get and attr(String key, String value) to set attributes
attributes() to get all attributes
id(), className() and classNames()
text() to get and text(String value) to set the text content
html() to get and html(String value) to set the inner HTML content
outerHtml() to get the outer HTML value
data() to get data content (e.g. of script and style tags)
tag() and tagName()
修改API
1
2
3
4
append(String html), prepend(String html)
appendText(String text), prependText(String text)
appendElement(String tagName), prependElement(String tagName)
html(String value)
通過select語法定位元素
這個不好用文字表達,直接看官網(wǎng) 文檔吧.
時間倉促,難免有不少錯誤,還往指正。