【发布时间】:2018-09-07 23:43:43
【问题描述】:
我目前正在为一家公司开发 Java 桌面应用程序,他们要求我从网页中提取最后 5 篇文章并将它们显示在应用程序中。为此,我当然需要一个 html 解析器,并且我直接想到了 JSoup。但我的问题是我该怎么做呢?我从这个问题中找到了一个简单的例子:Example: How to “scan” a website (or page) for info, and bring it into my program?
使用此代码:
package com.stackoverflow.q2835505;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
public class Test {
public static void main(String[] args) throws Exception {
String url = "https://stackoverflow.com/questions/2835505";
Document document = Jsoup.connect(url).get();
String question = document.select("#question .post-text").text();
System.out.println("Question: " + question);
Elements answerers = document.select("#answers .user-details a");
for (Element answerer : answerers) {
System.out.println("Answerer: " + answerer.text());
}
}
}
这段代码是由 BalusC 编写的,我理解它,但是当链接不固定时我该怎么做,例如大多数报纸的情况。为了简单起见,我将如何从这个新闻页面中提取例如最后 5 篇文章:News? 我无法使用 rss 提要,因为我的老板希望显示完整的文章。
【问题讨论】:
-
你可以试试hacker news链接吗?顺便问一下你得到的错误是什么?
-
谢谢 Gauthaman 和 Elliot,但我已经考虑过这一点,我的老板不想要 rss 提要,他希望完成所有 5 篇文章,而不是预览,就像它显示在 rss 提要中一样。
标签: java html web-scraping jsoup