2012-03-08 26 views
6

Tôi dường như không tải được trong một tệp html cục bộ, sử dụng thư viện Jsoup. Hoặc ít nhất nó dường như không nhận ra nó. Tôi hardcoded html chính xác trong tập tin địa phương (như var 'html') và khi tôi chuyển sang đó thay vì một tập tin đầu vào mã hoạt động hoàn hảo. Nhưng tập tin được đọc trên cả hai lần.Làm cách nào để tải tệp html cục bộ vào 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*/ 

quả khi:
Document doc = Jsoup.parseBodyFragment (html)

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

quả khi:
Document doc = Jsoup.parseBodyFragment (đầu vào)

The file can be read: true 
nothing! 

Trả lời

9

m của bạn istake giả định rằng Jsoup.parseBodyFragment() biết liệu bạn có truyền tên tệp có chứa đánh dấu html hay chuỗi chứa đánh dấu html hay không.

Jsoup.parseBodyFragment(input) hy vọng rằng inputString có chứa đánh dấu html chứ không phải tên tệp.

Để yêu cầu nó để phân tích từ một tập tin sử dụng JSoup.parse(File in, String charsetName) phương pháp thay vì:

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

Nope điều đó không làm các trick trong hai. –

+0

Cập nhật: trong câu trả lời ban đầu của tôi, tôi đã nhầm lẫn trong chuỗi '' input'' thay vì đối tượng '' File'' '' in''. Ngoài ra, bạn sẽ phải bọc mã trong khối 'try-catch'' để làm cho nó hoạt động. – holygeek

+0

Cảm ơn bạn! Sự trao đổi từ một String thành một loại tệp đã làm việc một sự quyến rũ. –

Các vấn đề liên quan