关于如何把baidu/google嵌入到自己的系统当中去做法

项目当中需要进行元搜索。选择了百度。也可以选择谷歌。两者的处理方式是一样的。

(1):页面输入:日全食。请求到struts2中的action中。

 public String findSearchKeyWordByBaidu() {
       List<WebScout> webScouts = Utilities.getWebScouts(keyWord, webpage);//分析百度页面处理。
      Collections.sort(webScouts);//排序
      this.getRequest().setAttribute("webScouts", webScouts);
      this.getRequest().setAttribute("keywordName", this.keyWord);
      this.getRequest().setAttribute("webpage", this.webpage);
      return "webScouts";//所返回struts.xml中的name值。
 }

(2):getWebScouts这个方法中是通过java正则表达式处理了百度页面。大家可以在百度中随便搜索一个关键字,然后查看下源文件。分析下源文件中每一条记录的特点。

 public static List<WebScout> getWebScouts(String keyword, int key) {
  List<WebScout> webs = new ArrayList<WebScout>();
  keyword = keyword.replaceAll("\\s|\\,|\\-", "+");
//  keyword = "北京+日全食+上海";
  String regx = "<table\\sborder=\"0\".*?><tr><td.*?><a\\sοnmοusedοwn=.*?><font.*?>(.*?)</a><br><font.*?>(.*?)<br><font.*?>(.*?)\\s\\d{1,4}K\\s(\\d{4}-\\d{1,2}-\\d{1,2}).*?</font>\\s-\\s<a\\shref=\"(.*?)\"\\starget=\"_blank\"\\sclass=m>百度快照</a>\\s<br>(<a.*?</a>)?</font></td></tr></table>";   //处理源文件
//  String urlSource = "http://www.baidu.com/s?wd=" + keyword;
  //String pageUrlSource = "http://www.baidu.com/s?lm=0&si=&rn=10&ie=gb2312&ct=0&wd="+keyword+"&pn="+key;
  String urlSource = "http://www.baidu.com/s?lm=0&si=&rn=10&ie=gb2312&ct=0&wd="+keyword+"&pn="+key;
  //String urlSource = "http://www.baidu.com/s?ie=gb2312&bs=%B1%B1%BE%A9+%C8%CB%C3%F1&sr=&z=&cl=3&f=8&wd=%B1%B1%BE%A9+%C8%CB%C3%F1&ct=0";
  //将用户输入的url字符串传入URL类对象中
  try {
   URL url = new URL(urlSource);
   //创建URLConnection对象,用URL的openConnection方法将连接通过返回给URLConnection对象
   HttpURLConnection c = (HttpURLConnection) url.openConnection();
   //用URLConnection的connect()方法建立连接
   c.connect();
   
   InputStream is = c.getInputStream();
   BufferedReader br = new BufferedReader(new InputStreamReader(is));

   StringBuffer sb = new StringBuffer();
   String line = br.readLine();
   while (line != null) {
    sb.append(line);
    line = br.readLine();
   }
   is.close();
   br.close();
   Pattern pattern = Pattern.compile(regx);
   Matcher matcher = pattern.matcher(sb);
   WebScout webScout = null;

   /**封装到一个bean中**/
   while(matcher.find()) {
    webScout = new WebScout();
    webScout.setTitle(matcher.group(1));
    webScout.setContent(matcher.group(2));
    webScout.setWebUrl(matcher.group(3));
    webScout.setTime(matcher.group(4));
    webScout.setKuaizhao(matcher.group(5));
    webs.add(webScout);
   }
  } catch (Exception e) {
   e.printStackTrace();
  }
  return webs;
 }

 

上面这个方法可以直接那过来测试的。

(3):struts.xml中返回到一个.jsp。然后把webScouts进行循环处理就ok了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值