2012-03-08 49 views
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! 

回答

9

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

Jsoup.parseBodyFragment(input)預計input是一個String包含html標記,而不是文件名。

要問它從一個文件來分析使用JSoup.parse(File in, String charsetName)方法來代替:

File in = new File(input); 
Document doc = JSoup.parse(in, null); 
+0

都能跟得上是沒有做的伎倆無論是。 – 2012-03-08 01:34:18

+0

更新:在我的原始答案中,我錯誤地傳遞了字符串''input''而不是''File''對象''in''。你也必須在「try-catch」塊中包裝代碼才能使其工作。 – holygeek 2012-03-08 01:53:49

+0

謝謝!從字符串到文件類型的交換是一種魅力。 – 2012-03-08 03:18:54

相關問題