您好,我在维基百科中有一个个性页面,我想用 java 源代码从主要部分提取代码 HTML。
你有什么想法?
使用 Jsoup,特别是选择器语法。
Document doc = Jsoup.parse(new URL("http://en.wikipedia.org/", 10000);
Elements interestingParts = doc.select("div.interestingClass");
//get the combined HTML fragments as a String
String selectedHtmlAsString = interestingParts.html();
//get all the links
Elements links = interestingParts.select("a[href]");
//filter the document to include certain tags only
Whitelist allowedTags = Whitelist.simpleText().addTags("blockquote","code", "p");
Cleaner cleaner = new Cleaner(allowedTags);
Document filteredDoc = cleaner.clean(doc);
它是一个非常有用的 API,用于解析 HTML 页面和提取所需数据。
对于维基百科有 API:http ://www.mediawiki.org/wiki/API:Main_page
请注意,这将返回 HTML 源代码的 STRING(某种类型的 blob),而不是格式良好的内容项。
我自己用这个——我有一个小片段可以满足我的需要。传入 url、任何开始和停止文本或布尔值以获取所有内容。
public static String getPage(
String url,
String booleanStart,
String booleanStop,
boolean getAll) throws Exception {
StringBuilder page = new StringBuilder();
URL iso3 = new URL(url);
URLConnection iso3conn = iso3.openConnection();
BufferedReader in = new BufferedReader(
new InputStreamReader(
iso3conn.getInputStream()));
String inputLine;
if (getAll) {
while ((inputLine = in.readLine()) != null) {
page.append(inputLine);
}
} else {
boolean save = false;
while ((inputLine = in.readLine()) != null) {
if (inputLine.contains(booleanStart))
save = true;
if (save)
page.append(inputLine);
if (save && inputLine.contains(booleanStop)) {
break;
}
}
}
in.close();
return page.toString();
}