如何将本地html文件加载到Jsoup中?

问题描述 投票:7回答:1

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

结果时间: Document doc = Jsoup.parseBodyFragment(html)

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

结果时间: Document doc = Jsoup.parseBodyFragment(输入)

The file can be read: true
nothing!
java html jsoup
1个回答
11
投票

你的错误是假设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);
© www.soinside.com 2019 - 2024. All rights reserved.