Jsoup加載HTML的三種方式


轉載:http://www.javacui.com/opensource/464.html

Jsoup加載HTML的三種方式,上一篇說的只是一種方式,直接從HTTP源網站獲取。


從字符串解析

來自用戶輸入,一個文件或一個網站的HTML字符串,你可能需要對它進行解析並取其內容,或校驗其格式是否完整,或想修改它。

?
1
2
3
String html = "<html><head><title>First parse</title></head>"
  "<body><p>from www.javacui.com</p></body></html>";
Document doc = Jsoup.parse(html);

只要解析的不是空字符串,就能返回一個結構合理的文檔,其中包含(至少) 一個head和一個body元素。

一旦擁有了一個Document,你就可以使用Document中適當的方法或它父類 Element和Node中的方法來取得相關數據。

實用示例:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package com.cui.test;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
/**
 * 從字符串解析HTML
 * @author java小強
 */
public class StringHtmlSpider {
    public static void main(String[] args) {
        try {
            String html = "<html><head><title>First parse</title></head>"
                    "<body><p>from www.javacui.com</p></body></html>";
            Document doc = Jsoup.parse(html);
            Elements elements = doc.getElementsByTag("p");// 根據標籤獲取
            Element e = elements.get(0);// 因爲我知道只有一個p
            System.out.println(e.text());
            // 打印 from www.javacui.com
        catch (Exception e) {
            e.printStackTrace();
        }
    }
}


從本地文件加載

在本機硬盤上有一個HTML文件,需要對它進行解析從中抽取數據或進行修改。本示例HTML文件內容和上面示例字符串內容一致。

?
1
2
File input = new File("D:\\javacui.html");
Document doc = Jsoup.parse(input, "UTF-8");

這個方法用來加載和解析一個HTML文件。如在加載文件的時候發生錯誤,將拋出IOException,應作適當處理。

實用示例:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package com.cui.test;
import java.io.File;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
/**
 * 從本地文件解析HTML
 * @author java小強
 */
public class LocalDiskSpider {
    public static void main(String[] args) {
        try {
            File input = new File("D:\\javacui.html");
            Document doc = Jsoup.parse(input, "UTF-8");
            Elements elements = doc.getElementsByTag("p");// 根據標籤獲取
            Element e = elements.get(0);// 因爲我知道只有一個p
            System.out.println(e.text());
            // 打印 from www.javacui.com
        catch (Exception e) {
            e.printStackTrace();
        }
    }
}


來自網絡

你需要從一個網站獲取和解析一個HTML文檔,並查找其中的相關數據。

?
1
2
Document doc = Jsoup.connect("http://www.javacui.com/").get();
String title = doc.title();

connect(String url) 方法創建一個新的 Connection, 和 get() 取得和解析一個HTML文件。如果從該URL獲取HTML時發生錯誤,便會拋出 IOException,應適當處理。

Connection 接口還提供一個方法鏈來解決特殊請求,具體如下:

?
1
2
3
4
5
6
Document doc = Jsoup.connect("http://example.com")
  .data("query""Java")
  .userAgent("Mozilla")
  .cookie("auth""token")
  .timeout(3000)
  .post();

這個方法只支持Web URLs (http和https 協議)。

使用代碼參考:http://www.javacui.com/opensource/463.html 


Jsoup加載HTML的三種方式


參考官網:https://jsoup.org/ 


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章