【问题标题】:How to parse this site with Jsoup or another parser?如何用 Jsoup 或其他解析器解析这个站点?
【发布时间】:2013-09-10 15:34:11
【问题描述】:

我正在尝试解析在其标头中没有定义编码的页面,在 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);

感谢您的任何建议!

【问题讨论】:

  • Jsoup.parse(new URL(url), 1000); 有什么问题?对我来说这似乎是正确的......

标签: java jsoup


【解决方案1】:

使用 URL 时,chapters 49 of the cookbook 建议使用 Jsoup.connect(...).get()Chapter 5 建议在从本地文件加载文档时使用 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.");
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-28
    • 1970-01-01
    • 1970-01-01
    • 2012-02-27
    相关资源
    最近更新 更多