当我们需要从网络上获取资源的时候,我们一般的做法就是通过浏览器打开某个网站,然后将我们需要的东西下载或者保存下来。

但是,当我们需要大量下载的时候,这个时候通过人工一个个的去点击下载,就显得太没有效率了。这个时候我们就可以通过程序来实现批量的获取资源的方式,我们称之为爬虫。也就是从网络上的站点爬取资源的意思。

 

那么在java中要实现网络爬虫,就必须要使用到java中的java.net包中的一些类。

 举例:

package com.fuwh;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class Crawler01 {

    public static void main(String[] args) {
        
        String urlStr="http://www.cnblogs.com/zerotomax/";
        try {
            URL url=new URL(urlStr);
                HttpURLConnection conn= (HttpURLConnection) url.openConnection();
                conn.connect();
                InputStream in=conn.getInputStream();
                BufferedReader read=new BufferedReader(new InputStreamReader(in));
                StringBuffer sb=new StringBuffer();
                String s=read.readLine();
                while( s!=null) {
                    sb.append(s+"\r\n");
                    s=read.readLine();
                }
                
                System.out.println(sb.toString());
                in.close();
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}
View Code

相关文章:

  • 2022-12-23
  • 2021-09-03
  • 2021-06-13
  • 2021-11-13
  • 2021-11-28
  • 2021-12-19
猜你喜欢
  • 2021-12-25
  • 2021-08-29
  • 2022-12-23
  • 2022-12-23
  • 2021-12-05
  • 2021-09-02
相关资源
相似解决方案