2012-03-08 70 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

相关问题