6
我似乎無法使用Jsoup庫加載本地html文件。或者至少它似乎沒有認識到它。我對本地文件中的確切html進行了硬編碼(如var'html'),當我切換到該文件而不是文件輸入時,代碼完美地工作。但是這個文件在兩種情況下都被讀取。如何將本地html文件加載到Jsoup中?
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(輸入)
The file can be read: true
nothing!
都能跟得上是沒有做的伎倆無論是。 – 2012-03-08 01:34:18
更新:在我的原始答案中,我錯誤地傳遞了字符串''input''而不是''File''對象''in''。你也必須在「try-catch」塊中包裝代碼才能使其工作。 – holygeek 2012-03-08 01:53:49
謝謝!從字符串到文件類型的交換是一種魅力。 – 2012-03-08 03:18:54