2015-06-23 34 views
0

我正在嘗試在每個美國城市的維基百科頁面。由於我不知道實際的URL,因此我會搜索並加載第一個結果。該URL簽名要做到這一點:如何使用Java加載維基百科頁面

http://en.wikipedia.org/wiki/Special:Search?go=Go&search=New+York%2C+NY

但是,它沒有得到任何東西,這是我的代碼:

String curWikiURL = "http://en.wikipedia.org/wiki/Special:Search?go=Go&search="+URLEncoder.encode("New York, NY", "UTF-8");; 
Scanner scanner = null; 
URLConnection connection = null; 
connection = new URL(curWikiURL).openConnection(); 
scanner = new Scanner(connection.getInputStream()); 
scanner.useDelimiter("\\Z"); 
content = scanner.next(); 
Document doc = Jsoup.parse(content); 
+0

這是維基百科對政策的使用爬蟲機器人就是這樣。你很可能會很快被封鎖。除非它不是爬蟲。 – h22

+0

我只是嘗試閱讀一次以收集一些數據來做一項研究,所以沒有任何網絡爬行。這更像是我自動完成一項任務,否則我將不得不手動完成任務。 – Bill

+0

您是否需要HTML中的信息或使用JSON API可以作爲選項? –

回答

1

你不必做所有的連接和東西JSoup庫可以處理所有these.Check如下

String url = "https://en.wikipedia.org/w/api.php?action=query&titles=Main%20Page&prop=revisions&rvprop=content&format=jsonfm "; 
    org.jsoup.nodes.Document document = (org.jsoup.nodes.Document) Jsoup 
      .connect(url).followRedirects(false).timeout(60000).get(); 
    org.jsoup.select.Elements elements = ((org.jsoup.nodes.Document) document) 
      .body().children(); 
for (Element element : elements) { 
    System.out.println(element); 
} 
0

使用它象下面這樣:

https://en.wikipedia.org/w/api.php?action=query&titles=Main%20Page&prop=revisions&rvprop=content&format=jsonfm 

這就是你使用MediaWiki API的方法。

入住這裏查看更多詳情 - https://www.mediawiki.org/wiki/API:Main_page