美文网首页
网页图片抓取

网页图片抓取

作者: CrazyGod | 来源:发表于2016-04-13 14:15 被阅读68次

一个很简单的网站图片抓取功能

全部使用jdk的基本功能,没有用任何包
不要谈什么效率,什么规范,要的就是立即看懂,拿着就改
不好意思,连正则都懒得用
也没用开源的爬虫软件。。。。。。

主要分两部分

1.找出连接

public class GetWebContent {
    /**
     * 获取html内容
     * @param domain
     * @return
     */
    public static String getWebCon(String path) {
        // System.out.println("开始读取内容...("+domain+")");
        StringBuffer sb = new StringBuffer();
        try {
            java.net.URL url = new java.net.URL(path);
            BufferedReader in = new BufferedReader(new InputStreamReader(url
                    .openStream()));
            String line;
            while ((line = in.readLine()) != null) {
                sb.append(line);
            }
            in.close();
        } catch (Exception e) { // Report any errors that arise
            sb.append(e.toString());
            System.err.println(e);
            System.err
                    .println("Usage:   java   HttpClient   <URL>   [<filename>]");
        }
        return sb.toString();
    }
     
    /**
     * 下载指定格式链接
     * @param path 图片所在网页
     * @param begin 图片路径开始
     * @param end 图片路径结尾
     */
    public static void uploadImage(String path,String begin,String end){
        Map<String,String> map=new HashMap<>();
        String a=getWebCon(path);
        String[] as=a.split(begin);
        for (int j = 1; j < as.length-1; j++) {
            String xxx = as[j].split(end)[0];
            String url=begin+xxx+end;
            if (map.containsKey(url))  continue;
            try {
                DownloadImage.download(url);
                map.put(url, "111");
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }           
        }
        
    }
}

2.下载图片

public class DownloadImage {
    
    private  static final String FILE_PATH="D:\\image\\";
 
    public static void download(String urlString) throws Exception {
        // 构造URL
        String filename=System.currentTimeMillis()+"-"+(int)(Math.random()*10000)+".jpg";
        String savePath=FILE_PATH;
        URL url = new URL(urlString);
        // 打开连接
        URLConnection con = url.openConnection();
        //设置请求超时为5s
        con.setConnectTimeout(5*1000);
        // 输入流
        InputStream is = con.getInputStream();
    
        // 1K的数据缓冲
        byte[] bs = new byte[1024];
        // 读取到的数据长度
        int len;
        // 输出的文件流
       File sf=new File(savePath);
       if(!sf.exists()){
           sf.mkdirs();
       }
       OutputStream os = new FileOutputStream(sf.getPath()+"\\"+filename);
        // 开始读取
        while ((len = is.read(bs)) != -1) {
          os.write(bs, 0, len);
        }
        // 完毕,关闭所有链接
        os.close();
        is.close();
    } 

}

相关文章

网友评论

      本文标题:网页图片抓取

      本文链接:https://www.haomeiwen.com/subject/tdnwlttx.html