`

使用Java调用谷歌搜索

    博客分类:
  • j2se
 
阅读更多

转自:http://yangshangchuan.iteye.com/blog/1961059

 

search-demo托管于github

 

search-demo演示了如何利用Java来调用百度搜索和谷歌搜索,更多细节请到github上查看search-demo

 

自己没搜索引擎,又想要大规模的数据源,怎么办?可以对百度搜索和谷歌搜索善加利用,以小搏大,站在巨人的肩膀上。有很多的应用场景可以很巧妙地借助百度搜索和谷歌搜索来实现,比如网站的新闻采集,比如技术、品牌的新闻跟踪,比如知识库的收集,比如人机问答系统等,我之前做的一个准确率达百分之九十几的人机问答系统的数据源,其中一部分就是充分利用了百度搜索和谷歌搜索。在此演示的技术的基础上,可以容易地扩展到其他的搜索引擎,可以借鉴使用的NekoHTML+XPath技术,轻松获取页面的自定义的内容。
 

Java代码  收藏代码
  1. package org.apdplat.demo.search;  
  2.   
  3. import java.io.IOException;  
  4. import java.io.InputStream;  
  5. import java.io.UnsupportedEncodingException;  
  6. import java.net.URLEncoder;  
  7. import java.util.ArrayList;  
  8. import java.util.List;  
  9.   
  10. import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;  
  11. import org.apache.commons.httpclient.HttpClient;  
  12. import org.apache.commons.httpclient.HttpStatus;  
  13. import org.apache.commons.httpclient.methods.GetMethod;  
  14. import org.apache.commons.httpclient.params.HttpMethodParams;  
  15. import org.json.JSONArray;  
  16. import org.json.JSONException;  
  17. import org.json.JSONObject;  
  18. import org.slf4j.Logger;  
  19. import org.slf4j.LoggerFactory;  
  20.   
  21. public class GoogleSearcher {  
  22.   
  23.     private static final Logger LOG = LoggerFactory.getLogger(GoogleSearcher.class);  
  24.   
  25.     public static List<Webpage> searchGoogle(String url) {  
  26.         List<Webpage> webpages = new ArrayList<>();  
  27.         try {  
  28.             HttpClient httpClient = new HttpClient();  
  29.             GetMethod getMethod = new GetMethod(url);  
  30.   
  31.             httpClient.executeMethod(getMethod);  
  32.             getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,  
  33.                     new DefaultHttpMethodRetryHandler());  
  34.   
  35.             int statusCode = httpClient.executeMethod(getMethod);  
  36.             if (statusCode != HttpStatus.SC_OK) {  
  37.                 LOG.error("搜索失败: " + getMethod.getStatusLine());  
  38.                 return null;  
  39.             }  
  40.             InputStream in = getMethod.getResponseBodyAsStream();  
  41.             byte[] responseBody = Tools.readAll(in);  
  42.             String response = new String(responseBody, "UTF-8");  
  43.             LOG.debug("搜索返回数据:" + response);  
  44.             JSONObject json = new JSONObject(response);  
  45.             String totalResult = json.getJSONObject("responseData").getJSONObject("cursor").getString("estimatedResultCount");  
  46.             int totalResultCount = Integer.parseInt(totalResult);  
  47.             LOG.info("搜索返回记录数: " + totalResultCount);  
  48.   
  49.             JSONArray results = json.getJSONObject("responseData").getJSONArray("results");  
  50.   
  51.             LOG.debug("搜索结果:");  
  52.             for (int i = 0; i < results.length(); i++) {  
  53.                 Webpage webpage = new Webpage();  
  54.                 JSONObject result = results.getJSONObject(i);  
  55.                 //提取标题  
  56.                 String title = result.getString("titleNoFormatting");  
  57.                 LOG.debug("标题:" + title);  
  58.                 webpage.setTitle(title);  
  59.                 //提取摘要  
  60.                 String summary = result.get("content").toString();  
  61.                 summary = summary.replaceAll("<b>""");  
  62.                 summary = summary.replaceAll("</b>""");  
  63.                 summary = summary.replaceAll("\\.\\.\\.""");  
  64.                 LOG.debug("摘要:" + summary);  
  65.                 webpage.setSummary(summary);  
  66.                 //从URL中提取正文  
  67.                 String _url = result.get("url").toString();  
  68.                 webpage.setUrl(_url);  
  69.                 String content = Tools.getHTMLContent(_url);  
  70.                 LOG.debug("正文:" + content);  
  71.                 webpage.setContent(content);  
  72.                 webpages.add(webpage);  
  73.             }  
  74.         } catch (IOException | JSONException | NumberFormatException e) {  
  75.             LOG.error("执行搜索失败:", e);  
  76.         }  
  77.         return webpages;  
  78.     }  
  79.   
  80.     public static void main(String args[]) {  
  81.         String query = "杨尚川";  
  82.         try {  
  83.             query = URLEncoder.encode(query, "UTF-8");  
  84.         } catch (UnsupportedEncodingException e) {  
  85.             LOG.error("url构造失败", e);  
  86.             return;  
  87.         }  
  88.         String url = "http://ajax.googleapis.com/ajax/services/search/web?start=0&rsz=large&v=1.0&q=" + query;  
  89.         List<Webpage> webpages = searchGoogle(url);  
  90.         if (webpages != null) {  
  91.             int i = 1;  
  92.             for (Webpage webpage : webpages) {  
  93.                 LOG.info("搜索结果 " + (i++) + " :");  
  94.                 LOG.info("标题:" + webpage.getTitle());  
  95.                 LOG.info("URL:" + webpage.getUrl());  
  96.                 LOG.info("摘要:" + webpage.getSummary());  
  97.                 LOG.info("正文:" + webpage.getContent());  
  98.                 LOG.info("");  
  99.             }  
  100.         } else {  
  101.             LOG.error("没有搜索到结果");  
  102.         }  
  103.     }  
  104. }  
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics