小男孩‘自慰网亚洲一区二区,亚洲一级在线播放毛片,亚洲中文字幕av每天更新,黄aⅴ永久免费无码,91成人午夜在线精品,色网站免费在线观看,亚洲欧洲wwwww在线观看

分享

Java解析Html

 quasiceo 2015-04-23

Java解析Html

| Comments

最近用到了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)文檔吧.

時間倉促,難免有不少錯誤,還往指正。

Comments

  • 還沒有評論,沙發(fā)等你來搶

社交賬號登錄:


    本站是提供個人知識管理的網(wǎng)絡(luò)存儲空間,所有內(nèi)容均由用戶發(fā)布,不代表本站觀點。請注意甄別內(nèi)容中的聯(lián)系方式、誘導購買等信息,謹防詐騙。如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請點擊一鍵舉報。
    轉(zhuǎn)藏 分享 獻花(0

    0條評論

    發(fā)表

    請遵守用戶 評論公約

    類似文章 更多