Jsoup的簡(jiǎn)單認(rèn)識(shí)及使用

jsoup 是一款Java 的HTML解析器力试,可直接解析某個(gè)URL地址肪虎、HTML文本內(nèi)容豌研。它提供了一套非常省力的API,可通過(guò)DOM贬丛,CSS以及類似于jQuery的操作方法來(lái)取出和操作數(shù)據(jù)撩银。

話不多說(shuō) 下面直接來(lái)整合一個(gè)小案例來(lái)測(cè)試一下:
先做準(zhǔn)備工作,我們一共需要用到4個(gè)jar包
1.JSoup Java HTML Parser的jar包
2.JUnit的jar包
3.Apache Commons IO的jar包
4.Apache Commons Lang的jar包

    <!-- https://mvnrepository.com/artifact/junit/junit -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.jsoup/jsoup -->
        <dependency>
            <groupId>org.jsoup</groupId>
            <artifactId>jsoup</artifactId>
            <version>1.8.3</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.4</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 -->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.4</version>
        </dependency>

點(diǎn)進(jìn)Jsoup的源碼可以看到構(gòu)造方法被私有了,都是靜態(tài)方法,就是一個(gè)簡(jiǎn)單的工具類豺憔。那么來(lái)嘗試一下吧.

//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package org.jsoup;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import org.jsoup.helper.DataUtil;
import org.jsoup.helper.HttpConnection;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Document.OutputSettings;
import org.jsoup.parser.Parser;
import org.jsoup.safety.Cleaner;
import org.jsoup.safety.Whitelist;

public class Jsoup {
    private Jsoup() {
    }

    public static Document parse(String html, String baseUri) {
        return Parser.parse(html, baseUri);
    }

    public static Document parse(String html, String baseUri, Parser parser) {
        return parser.parseInput(html, baseUri);
    }

    public static Document parse(String html) {
        return Parser.parse(html, "");
    }

    public static Connection connect(String url) {
        return HttpConnection.connect(url);
    }

    public static Document parse(File in, String charsetName, String baseUri) throws IOException {
        return DataUtil.load(in, charsetName, baseUri);
    }

    public static Document parse(File in, String charsetName) throws IOException {
        return DataUtil.load(in, charsetName, in.getAbsolutePath());
    }

    public static Document parse(InputStream in, String charsetName, String baseUri) throws IOException {
        return DataUtil.load(in, charsetName, baseUri);
    }

    public static Document parse(InputStream in, String charsetName, String baseUri, Parser parser) throws IOException {
        return DataUtil.load(in, charsetName, baseUri, parser);
    }

    public static Document parseBodyFragment(String bodyHtml, String baseUri) {
        return Parser.parseBodyFragment(bodyHtml, baseUri);
    }

    public static Document parseBodyFragment(String bodyHtml) {
        return Parser.parseBodyFragment(bodyHtml, "");
    }

    public static Document parse(URL url, int timeoutMillis) throws IOException {
        Connection con = HttpConnection.connect(url);
        con.timeout(timeoutMillis);
        return con.get();
    }

    public static String clean(String bodyHtml, String baseUri, Whitelist whitelist) {
        Document dirty = parseBodyFragment(bodyHtml, baseUri);
        Cleaner cleaner = new Cleaner(whitelist);
        Document clean = cleaner.clean(dirty);
        return clean.body().html();
    }

    public static String clean(String bodyHtml, Whitelist whitelist) {
        return clean(bodyHtml, "", whitelist);
    }

    public static String clean(String bodyHtml, String baseUri, Whitelist whitelist, OutputSettings outputSettings) {
        Document dirty = parseBodyFragment(bodyHtml, baseUri);
        Cleaner cleaner = new Cleaner(whitelist);
        Document clean = cleaner.clean(dirty);
        clean.outputSettings(outputSettings);
        return clean.body().html();
    }

    public static boolean isValid(String bodyHtml, Whitelist whitelist) {
        Document dirty = parseBodyFragment(bodyHtml, "");
        Cleaner cleaner = new Cleaner(whitelist);
        return cleaner.isValid(dirty);
    }
}
Jsoup的parse方法重載了很多參數(shù),有讀取字符串的,file文件的.下面以簡(jiǎn)單的例子來(lái)做演示.
import org.apache.commons.io.FileUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import org.junit.Test;

import java.io.File;
import java.io.IOException;
import java.net.URL;

public class JsoupDemo {

    //解析url
    @Test
    public void urldemo() throws IOException {

        //解析url,返回一個(gè)文檔對(duì)象
        Document document =Jsoup.parse(new URL("http://www.baidu.com"),1000);

        //獲取名字為title標(biāo)簽的元素
//        String title =document.getElementsByTag("title").first().text();

        Elements elements =document.getElementsByTag("title");

        System.out.println(elements.text());
    }

    @Test
    public void stringdemo() throws Exception {

        //使用工具類讀取文件,獲取字符串
        String str=FileUtils.readFileToString(new File("C:\\Users\\asus\\Desktop\\嗶哩嗶哩 (゜-゜)つロ 干杯_-bilibili.html"),"utf8");

        //解析字符串额获,返回文檔對(duì)象
        Document document=Jsoup.parse(str);

        //獲取第一個(gè)名為title標(biāo)簽的內(nèi)容
        String string=document.getElementsByTag("title").first().text();

        //打印輸出
        System.out.println(string);
    }


    @Test
    public void filedemo() throws IOException {

        //解析文件,返回dom對(duì)象
        Document document=Jsoup.parse(new File("C:\\Users\\asus\\Desktop\\嗶哩嗶哩 (゜-゜)つロ 干杯_-bilibili.html"),"utf8");

        //獲取第一個(gè)名為title標(biāo)簽的內(nèi)容
        String str=document.getElementsByTag("title").first().text();

        //打印輸出
        System.out.println(str);
    }
}

Jsoup還有很多封裝好的方法就不一一演示了.

DOM對(duì)象封裝的方法:

document.getElementById();//根據(jù)id查詢?cè)?document.getElementsByTag();//根據(jù)標(biāo)簽獲取元素
document.getElementsByClass();//根據(jù)class獲取元素
document.getElementsByAttribute();//根據(jù)屬性獲取元素

Element封裝的方法:
element.id();//從元素中獲取id
element.className();//從元素中獲取className
element.attr();//從元素中獲取屬性的值attr
element.attributes();//從元素中獲取所有屬性attributes
element.text();//從元素中獲取文本內(nèi)容text


?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末够庙,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子抄邀,更是在濱河造成了極大的恐慌耘眨,老刑警劉巖,帶你破解...
    沈念sama閱讀 219,039評(píng)論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件境肾,死亡現(xiàn)場(chǎng)離奇詭異剔难,居然都是意外死亡,警方通過(guò)查閱死者的電腦和手機(jī)准夷,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,426評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門钥飞,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)莺掠,“玉大人衫嵌,你說(shuō)我怎么就攤上這事〕垢眩” “怎么了楔绞?”我有些...
    開(kāi)封第一講書人閱讀 165,417評(píng)論 0 356
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)唇兑。 經(jīng)常有香客問(wèn)我酒朵,道長(zhǎng),這世上最難降的妖魔是什么扎附? 我笑而不...
    開(kāi)封第一講書人閱讀 58,868評(píng)論 1 295
  • 正文 為了忘掉前任蔫耽,我火速辦了婚禮,結(jié)果婚禮上留夜,老公的妹妹穿的比我還像新娘匙铡。我一直安慰自己,他們只是感情好碍粥,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,892評(píng)論 6 392
  • 文/花漫 我一把揭開(kāi)白布鳖眼。 她就那樣靜靜地躺著,像睡著了一般嚼摩。 火紅的嫁衣襯著肌膚如雪钦讳。 梳的紋絲不亂的頭發(fā)上,一...
    開(kāi)封第一講書人閱讀 51,692評(píng)論 1 305
  • 那天枕面,我揣著相機(jī)與錄音愿卒,去河邊找鬼。 笑死潮秘,一個(gè)胖子當(dāng)著我的面吹牛琼开,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播唇跨,決...
    沈念sama閱讀 40,416評(píng)論 3 419
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼稠通,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼衬衬!你這毒婦竟也來(lái)了?” 一聲冷哼從身側(cè)響起改橘,我...
    開(kāi)封第一講書人閱讀 39,326評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤滋尉,失蹤者是張志新(化名)和其女友劉穎,沒(méi)想到半個(gè)月后飞主,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體狮惜,經(jīng)...
    沈念sama閱讀 45,782評(píng)論 1 316
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,957評(píng)論 3 337
  • 正文 我和宋清朗相戀三年碌识,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了碾篡。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 40,102評(píng)論 1 350
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡筏餐,死狀恐怖开泽,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情魁瞪,我是刑警寧澤穆律,帶...
    沈念sama閱讀 35,790評(píng)論 5 346
  • 正文 年R本政府宣布,位于F島的核電站导俘,受9級(jí)特大地震影響峦耘,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜旅薄,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,442評(píng)論 3 331
  • 文/蒙蒙 一辅髓、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧少梁,春花似錦洛口、人聲如沸。這莊子的主人今日做“春日...
    開(kāi)封第一講書人閱讀 31,996評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至著洼,卻和暖如春樟遣,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背身笤。 一陣腳步聲響...
    開(kāi)封第一講書人閱讀 33,113評(píng)論 1 272
  • 我被黑心中介騙來(lái)泰國(guó)打工豹悬, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人液荸。 一個(gè)月前我還...
    沈念sama閱讀 48,332評(píng)論 3 373
  • 正文 我出身青樓瞻佛,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子伤柄,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,044評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容