我似乎无法在本地html文件中加载,使用Jsoup库。或者至少它似乎没有意识到这一点。我在本地文件(作为var ' html ')中硬编码了确切的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>结果时:
Jsoup.parseBodyFragment(input)文档doc =
The file can be read: true
nothing!发布于 2012-03-08 01:27:44
您的错误在于假设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);发布于 2021-11-15 13:44:52
这是针对Kotlin用户的;非常类似于Java版本:
val file = File("my-document.html")
val document = Jsoup.parse(file, "UTF-8")这是此方法的文档。
https://stackoverflow.com/questions/9611570
复制相似问题