项目当中需要进行元搜索。选择了百度。也可以选择谷歌。两者的处理方式是一样的。
(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了。