簡體   English   中英

如何將本地 html 文件加載到 Jsoup 中?

[英]How do I load a local html file into Jsoup?

我似乎無法使用 Jsoup 庫加載本地 html 文件。 或者至少它似乎沒有意識到它。 我在本地文件中硬編碼了確切的 html(作為 var 'html'),當我切換到它而不是文件輸入時,代碼完美地工作。 但是在這兩種情況下都會讀取該文件。

import java.io.File;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;


public class FileHtmlParser{

public String input;


//constructor
public FileHtmlParser(String inputFile){input = inputFile;}


//methods
public FileHtmlParser execute(){

    File file = new File(input);
    System.out.println("The file can be read: " + file.canRead());

    String html = "<html><head><title>First parse</title><meta>106</meta> <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" /></head>"
              + "<body><p>Parsed HTML into a doc.</p>" +
              "" +
              "<div id=\"navbar\">this is the div</div></body></html>";
            Document doc = Jsoup.parseBodyFragment(input);




    Elements content = doc.getElementsByTag("div");
    if(content.hasText()){System.out.println("result is " + content.outerHtml());}
    else System.out.println("nothing!");


    return this;
}

}/*endOfClass*/

結果時:
文檔 doc = Jsoup.parseBodyFragment(html)

The file can be read: true
result is <div id="navbar">
this is the div
</div>

結果時:
文檔 doc = Jsoup.parseBodyFragment(input)

The file can be read: true
nothing!

你的錯誤是假設Jsoup.parseBodyFragment()知道你是否傳遞了包含html標記的文件名或包含html標記的字符串。

Jsoup.parseBodyFragment(input)期望input是包含html標記的String ,而不是文件名。

要讓它從文件解析,請使用Jsoup.parse(File in, String charsetName)方法:

File in = new File(input);
Document doc = Jsoup.parse(in, null);

這適用於 Kotlin 用戶; 非常像 Java 版本:

val file = File("my-document.html")
val document = Jsoup.parse(file, "UTF-8")

這是此方法文檔

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM