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!
Nope điều đó không làm các trick trong hai. –
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
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ũ. –