在java中获取google的搜索结果

我在这个程序中得到了403响应代码,但是我需要200才能找回搜索结果,我该怎么办?

String url="http://www.google.com/search?q="; String charset="UTF-8"; String key="java"; String query = String.format("%s",URLEncoder.encode(key, charset)); URLConnection con = new URL(url+ query).openConnection(); BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; while ((inputLine = in.readLine()) != null) System.out.println(inputLine); in.close(); 

Google正在阻止Java发送的默认UserAgent。 您可以使用另一个并欺骗Google。 只需添加:

con.setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.4; en-US; rv:1.9.2.2) Gecko/20100316 Firefox/3.6.2");

在创建con之后和开始阅读之前。

尝试使用JSoup

 Document document = Jsoup .connect("http://www.google.com/search?q=" + query) .userAgent("Mozilla/5.0 (Windows NT 6.1; WOW64; rv:5.0) Gecko/20100101 Firefox/5.0") .get(); System.out.println(document.html()); 

对于提取链接,请使用选择器api 。

相关性:

   org.jsoup jsoup 1.7.3  

403响应很清楚。 谷歌服务器告诉你,你做事的方式不是一种既不被授权也不能容忍的方式。

Google禁止使用自动查询 ,使用它时,您可能会随时被阻止。

如果你想沿着这条路走下去,你将必须理解为什么你被阻止(用户代理,IP地址,标题指纹识别等等。有很多方法可以让他们知道你是不是机器人)

作为JSoup的替代方案,您可以使用此包 。

代码示例:

 Map parameter = new HashMap<>(); parameter.put("q", "Coffee"); parameter.put("location", "Portland"); GoogleSearchResults serp = new GoogleSearchResults(parameter); JsonObject data = serp.getJson(); JsonArray results = (JsonArray) data.get("organic_results"); JsonObject first_result = results.get(0).getAsJsonObject(); System.out.println("first coffee: " + first_result.get("title").getAsString());