1

我正在尝试解析在其标题中没有定义编码的页面,在 HTML 中它将 ISO-8859-1 定义为编码。Jsoup 无法使用默认设置解析它(HTMLunit 和 PHP 的 Simple HTML Dom Parser 默认也无法处理它)。即使我自己定义了 Jsoup 的编码,它仍然无法正常工作。想不通为什么。

这是我的代码:

    String url = "http://www.parkett.de";
    Document doc = null;
    try {
         doc = Jsoup.parse(new URL(url).openStream(), "ISO-8859-1", url);
        // doc = Jsoup.parse(new URL(url).openStream(), "CP1252", url);
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    Element extractHtml = null;
    Elements elements = null;
    String title = null;
    elements = doc.select("h1");
    if(!elements.isEmpty()) {
        extractHtml = elements.get(0);
        title = extractHtml.text();
    }
    System.out.println(title);

感谢您的任何建议!

4

1 回答 1

1

使用 URL 时,食谱的第 4 章和第9章建议使用. 第 5 章建议在从本地文件加载文档时使用。Jsoup.connect(...).get()Jsoup.parse()

public static void main(String[] args) {

    Document doc = null;

    try {
        doc = Jsoup.connect("http://www.parkett.de/").get();
    } catch (IOException e) {
        e.printStackTrace();
    }

    Element firstH1 = doc.select("h1").first();

    System.out.println((firstH1 != null) ? firstH1.text() : "First <h1> not found.");
}
于 2013-09-13T20:51:54.517 回答