黑马程序员技术交流社区

标题: 正则表达式,网络爬虫 [打印本页]

作者: 唐长智    时间: 2013-2-22 15:54
标题: 正则表达式,网络爬虫
这是我写的一个网络爬虫程序,在黑马的入学测试的网页中找“黑马”这个关键字,为什么爬虫只能爬到11个,但在网页源代码中确有51呢?
  1. import java.io.BufferedReader;
  2. import java.io.InputStreamReader;
  3. import java.net.URL;
  4. import java.util.regex.Matcher;
  5. import java.util.regex.Pattern;

  6. public class HeiMa {
  7.         public static void main(String[] args) throws Exception{
  8.                 URL url = new URL("http://bbs.itheima.com/forum-19-1.html");
  9.                
  10.                 BufferedReader br = new BufferedReader(new InputStreamReader(url.openConnection().getInputStream()));
  11.                 String regex = "[黑][马]";
  12.                 Pattern heimaregex = Pattern.compile(regex);
  13.                 String line = null;
  14.                 int x = 0;
  15.                 while((line = br.readLine())!=null){
  16.                         Matcher heimamacher = heimaregex.matcher(line);
  17.                         if(heimamacher.find()){
  18.                                 x++;
  19.                                 System.out.println(heimamacher.group());
  20.                         }
  21.                
  22.                 }
  23.                 System.out.println(x);
  24.         }
  25. }
复制代码

作者: 黑马-张洋    时间: 2013-2-22 16:51
我虽然未能彻底解决你的问题。但是我找2点问题,应该是解决问题的关键

1、我们在eclipse里面读到的代码和网页代码不一样(附件图和第一张和第二张对比可以看出)

2、我们在eclipse里面读到的代码没有读完。看我第三张图,读到一小半就结束了,注意看第10个黑马出现的地方

我没有学过javaweb,所以只能给你这些参考意见了

321.JPG (265.37 KB, 下载次数: 33)

321.JPG

作者: 唐长智    时间: 2013-2-22 19:29
是哈,我也发现了,这是为什么呢?




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2