Chinaunix首页 | 论坛 | 博客
  • 博客访问: 53685
  • 博文数量: 20
  • 博客积分: 1240
  • 博客等级: 中尉
  • 技术积分: 270
  • 用 户 组: 普通用户
  • 注册时间: 2008-05-02 09:47
文章存档

2010年(1)

2009年(5)

2008年(14)

我的朋友
最近访客

分类: Java

2008-09-24 23:15:39

要想抓取一个整站资源,首先必须要清楚的一点就是:你需要知道从哪一个入口,可以获得所有的资源路径。也就是说,你需要一个类似sitemap的东西来遍历所有站点资源。
好,就事论事,把我的爬虫放出去,要给他一个入口url。分析这个网站,从哪里可以得到这么一个url呢?
无独有偶,我想得到的是所有的谱子,而这个站长搞了一个分类,就是按照所有谱子歌手的字母进行了排序,因此,这个排序理论上是能够遍历全站的。
于是,第一步的程序是这么写的:(开发语言么随便,当然我要祭出我的宝物java)
 

    /*
     * get the 1st url (classed by a,b,c,d...)
     * */

    public static int get_1stURL(String url,File S_file){
        try{
             //String ur=""; //获取远程网上的信息

            URL MyURL=new URL(url);
            String str;
            URLConnection con=MyURL.openConnection();
            InputStreamReader ins=new InputStreamReader(con.getInputStream());
            BufferedReader in=new BufferedReader(ins);
            StringBuffer sb = new StringBuffer();
            while ((str=in.readLine())!=null)
            {
                sb.append(str);
            }
            in.close();
            
            Pattern p = Pattern.compile("(.*?)");
            Matcher m = p.matcher(sb.toString());

            BufferedWriter rw = new BufferedWriter(new FileWriter(S_file,true));
            int i = 0;
            while(m.find())
            {
                rw.write(index+"\n");
                rw.write(m.group(2).trim()+"\n");
                rw.write(m.group(1).trim()+"\n");
                i++;
                index++;
            }
            rw.close();
            return i;
        }
        catch (MalformedURLException mfURLe) {
            System.out.println("MalformedURLException: " + mfURLe);
            return -1;
        }
        catch (IOException ioe) {
            System.out.println("IOException: " + ioe);
            return -1;
             }
    }
 
}

具体我不详细说了,我说一下这个函数的大意:
1)首先获得入口url,如:, 假设这个是子母a的第一级链接;
2)读取这个url的所有内容到一个buffer里面去;
3)使用正则表达式分析这个buffer,过滤出第一季页面里面的歌手列表和二级url,并存在一个文件里面;

第一步工作就完成了,很简单吧?哈哈··记住,找到一个好的入口,就是成功了1半了。

阅读(713) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~