它非常简单,每个半结构化页面的过程都非常相似,您可以从中提取信息.
首先,您必须唯一地标识所需信息所在的DOM元素.最简单的方法是使用Web开发工具,例如Firefox中的Firebug,或者与IE捆绑在一起的工具(> 6,我认为)和Chrome.
以文章Potato为例,您会发现您感兴趣的< p> aragraph位于以下块中:
The potato [...]
[...]
[...]
换句话说,你想要找到第一个< p> div中的元素,名为mw-content-ltr.
然后,您只需要使用jsoup选择该元素,例如使用其选择器语法(这与jQuery非常相似):
public class WikipediaParser {
private final String baseUrl;
public WikipediaParser(String lang) {
this.baseUrl = String.format("http://%s.wikipedia.org/wiki/", lang);
}
public String fetchFirstParagraph(String article) throws IOException {
String url = baseUrl + article;
Document doc = Jsoup.connect(url).get();
Elements paragraphs = doc.select(".mw-content-ltr p");
Element firstParagraph = paragraphs.first();
return firstParagraph.text();
}
public static void main(String[] args) throws IOException {
WikipediaParser parser = new WikipediaParser("en");
String firstParagraph = parser.fetchFirstParagraph("Potato");
System.out.println(firstParagraph); // prints "The potato is a starchy [...]."
}
}