我想使用wikipedia中的文章鏈接創建圖表。所以我需要從父頁面提取超鏈接到下一個節點 - 文章。如何獲取維基百科文章中使用Jsoup的其他文章的鏈接?
我怎樣才能使用Jsoup,例如?我的問題是,我知道如何提取所有鏈接,但不僅僅需要。
預先感謝您。
我想使用wikipedia中的文章鏈接創建圖表。所以我需要從父頁面提取超鏈接到下一個節點 - 文章。如何獲取維基百科文章中使用Jsoup的其他文章的鏈接?
我怎樣才能使用Jsoup,例如?我的問題是,我知道如何提取所有鏈接,但不僅僅需要。
預先感謝您。
試試這個,
Document doc = Jsoup.connect("http://en.wikipedia.org/wiki/Boston").timeout(5000).get();
Element intro = doc.body().select("p").first();
while (intro.tagName().equals("p")) {
//here you will get an Elements object which you can
//iterate through to get the links in the intro
System.out.println(intro.select("a"));
intro = intro.nextElementSibling();
}
for (Element h2 : doc.body().select("h2")) {
if(h2.select("span").size() == 2) {
if (h2.select("span").get(1).text().equals("Geography")) {
Element nextsib = h2.nextElementSibling();
while (nextsib != null) {
if (nextsib.tagName().equals("p")) {
//here you will get an Elements object which you
//can iterate through to get the links in the
//geography section
System.out.println(nextsib.select("a"));
nextsib = nextsib.nextElementSibling();
} else if (nextsib.tagName().equals("h2")) {
nextsib = null;
} else {
nextsib = nextsib.nextElementSibling();
}
}
}
}
}
}
我做了我的一個個人項目類似的東西。
請參見:
try {
doc = Jsoup.connect("http://www.wikipedia.org/").get();
links = doc.select("a");
} catch (IOException e) {
e.printStackTrace();
}
String[] temp = new String[100]; //Should use ArrayList for this due to unknown number of URLS, I'm just giving an example
if (links != null) {
for(Element link : links){
String temp = link.attr("href");
}
}
doc.select("a")
選擇所有標籤與<a ..... />
在頁面上。
link.attr("href")
獲取這些標籤內的文章的URL。
考慮在for
循環中添加一個isValidLink
函數,以確保您抓取的維基百科鏈接實際上是一篇文章,而不僅僅是一個隨機鏈接。對於我的項目,我isValidLink
如下:
private boolean isValidURL(String temp){
if(temp.contains("thestar.com") && temp.length() > 75 && (temp.contains("/news/") || temp.contains("/business/") || temp.contains("/sports/") || temp.contains("/entertainment/") || temp.contains("/life/"))){
return true;
}
return false;
}
希望幫助了一點
告訴我們,你有extartcting所有的鏈接代碼,並界定什麼是你的「需要鏈接」。 – TDG