【问题标题】:How do I load a local html file into Jsoup?如何将本地 html 文件加载到 Jsoup 中?
【发布时间】:2012-03-25 13:50:15
【问题描述】:

我似乎无法使用 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!

【问题讨论】:

    标签: java html jsoup


    【解决方案1】:

    您的错误在于假设 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);
    

    【讨论】:

    • 更新:在我的原始答案中,我错误地传递了字符串 input 而不是 File 对象 in。此外,您必须将代码包装在 try-catch 块中以使其工作。
    • 知道如何在文件位于 assets 文件夹中的 Android 中使用它吗?
    【解决方案2】:

    这是给 Kotlin 用户的;很像 Java 版本:

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

    这里是documentations for this method

    【讨论】:

      猜你喜欢
      • 2011-06-06
      • 2011-10-27
      • 1970-01-01
      • 1970-01-01
      • 2017-04-23
      • 2020-12-28
      • 1970-01-01
      • 2021-12-27
      • 2013-01-18
      相关资源
      最近更新 更多