2015-06-23 42 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