日期:2014-05-20  浏览次数:20770 次

怎样抓取Google搜索结果?
为什么通过正则表达式分析google的搜索结果页面代码来抓取结果的标题和链接不成功,而百度的却能成功?

public class SaveURL{

public static String savepath_SaveURL="d:\\";//默认路径为D盘根目录
static String title=null;
static String link=null;
static String localFile=null;//保存为本地文件后的路径
static String res=null;

public static void go() {
//String url= "http://www.baidu.com/s?wd=accenture&rn=10";
String url="http://www.google.com/search?hl=en&newwindow=1&q=hello&start=0&sa=N&num=30";
  String content = getPage(url);//得到url所对应的网页的内容
   

// 对应百度<table border="0" cellpadding="0" cellspacing="0">等的正则表达式
// 为什么快照的链接没有被下载下来?
   
  //String reg = "<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\">.*?"+
//"<a.*? href=\"(.*?)\".*?>(.*?)</a>.*?</table>";

  //Google对应的正则式
String reg = "<h2 class=r>"+"<a href=\"(.*?)\".*?>(.*?)</a></h2>";
Pattern p = Pattern.compile(reg,Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
  Matcher m = p.matcher(content);
   
  int i = 1;

  while(m.find())
  {
  title=m.group(2).replaceAll("<.*?>", "");//正则表达式
  link=m.group(1);
 
  System.out.println("----------------------------------------------");
  System.out.println("第"+i+"个标题:"+title);
  System.out.println("第"+i+"个链接:"+link);  

  i++;
  }//end of while

}

  public static String getPage(String page) {
  try {
 
  URL url = new URL(page);
  HttpURLConnection con = (HttpURLConnection) url.openConnection();
   
// 以下是修正Server returned HTTP response code: 403 for URL的代码
// 通常是因为服务器的安全设置不接受Java程序作为客户端访问,解决方案是设置客户端的User Agent
  con.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0;Windows NT; DigExt)");
 
  BufferedReader reader = new BufferedReader(new InputStreamReader(
  con.getInputStream()));
  StringBuilder b = new StringBuilder();
  String line;
  while ((line = reader.readLine()) != null) {
  b.append(line);
  b.append("\r\n");
  }
  return b.toString();
  } catch (FileNotFoundException ex) {
  System.out.println("NOT FOUND:" + page);
  return null;
  } catch (ConnectException ex) {
  System.out.println("Timeout:" + page);
  return null;
  } catch (Exception ex) {
  ex.printStackTrace();
  return null;
  }
  }
   
  public static void main(String[] args){
  go();
  }

}



如果打开google的结果目录页,查看源代码的结构,是和百度的差别不大啊,就是google的每个结果都是放在一个<div></div>中<h2 class=r>里边,而百度里边的是放在一个<table></table>标签里,为什么Google的会得不到呢?

请高手帮忙解释下。
谢谢。

------解决方案--------------------
这个说到底还是程序问题,仔细推敲下代码吧,既然百度能抓了,google不成问题
------解决方案--------------------