我一直在尝试下载 Google 新闻 rss feed 的源代码。除了显示奇怪的链接外,它都已正确下载。
static String urlNotizie = "https://news.google.it/news/feeds?pz=1&cf=all&ned=it&hl=it&output=rss";
Document docHtml = Jsoup.connect(urlNotizie).get();
String html = docHtml.toString();
System.out.println(html);
输出:
<html>
<head></head>
<body>
<rss version="2.0">
<channel>
<generator>
NFE/1.0
</generator>
<title>Prima pagina - Google News</title>
<link />http://news.google.it/news?pz=1&ned=it&hl=it
<language>
it
</language>
<webmaster>
news-feedback@google.com
</webmaster>
<copyright>
&copy;2013 Google
</copyright> [...]
使用 URLConnection 我能够输出页面的正确源。但在解析过程中,我遇到了与上面相同的问题,它会吐出 <link />.
的列表。 (同样只有链接。解析其他东西效果很好)。 URL连接示例:
URL u = new URL(urlNotizie);
URLConnection yc = u.openConnection();
StringBuilder builder = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(
yc.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
builder.append("\n");
}
String html = builder.toString();
System.out.println("HTML " + html);
Document doc = Jsoup.parse(html);
Elements listaTitoli = doc.select("title");
Elements listaCategorie = doc.select("category");
Elements listaDescrizioni = doc.select("description");
Elements listaUrl = doc.select("link");
System.out.println(listaUrl);
最佳答案
Jsoup 被设计为 HTML parser ,而不是作为 XML(或 RSS)解析器。
HTML <link>
element被指定为没有任何主体。它将是 invalid有一个<link>
具有主体的元素,如 XML 中所示。
您可以使用 Jsoup 解析 XML,但需要显式 tell切换到 XML parsing mode .
替换
Document docHtml = Jsoup.connect(urlNotizie).get();
由
Document docXml = Jsoup.connect(urlNotizie).parser(Parser.xmlParser()).get();
关于java - HTML 未正确下载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20538864/