java--爬虫


import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

class reptile {

    // <img class="" src="图片地址"> ..

    // 默认正则 * + 都是贪婪模式: 尽可能多的匹配内容
    //         *?  +? 属于非贪婪模式
    public static void main(String[] args) throws IOException {
        Random random = new Random();
        String html = "图片1 <img class=\"样式\" src=\"3.png\"> 图片2 <img class=\"样式\" src=\"4.jpg\">";
        // 创建了正则对象, 其中() 表示一个分组,获取分组内容可以使用 group方法来获取
        HttpURLConnection connection = (HttpURLConnection)
                new URL("https://tieba.baidu.com/p/2256306796?red_tag=1781367364").openConnection();
        InputStream in = connection.getInputStream();
        BufferedReader buffer = new BufferedReader ( new InputStreamReader( in ) );
        while (true){
            String s = buffer.readLine ( );
            if (s==null){
                break;
            }
            Pattern pattern = Pattern.compile("<img class=\"BDE_Image\" src=\"(.*?)\">");
            // 开始匹配
            Matcher matcher = pattern.matcher(s);
            while(matcher.find()) {
                String s1 = matcher.group(1);
                //System.out.println(s1);
                String s2 = s1.substring(0,s1.indexOf(".jpg")+4);//图片路径
                //System.out.println(s2);
                downLoad(s2,random);
            }
        }
    }

    private static void downLoad(String s1, Random random) throws IOException {

        HttpURLConnection urlConnection = (HttpURLConnection) new URL(s1).openConnection();
        InputStream in = urlConnection.getInputStream();
        String i = random.nextInt()+"";
        FileOutputStream out = new FileOutputStream("E:\\图片\\" + i + ".png");
        while (true){
            byte[] bytes = new byte[1024 * 8];
            int len = in.read(bytes);
            if (len==-1){
                break;
            }
            out.write(bytes,0,len);
        }
    }
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值