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);
}
}
}
java--爬虫
最新推荐文章于 2024-06-06 01:44:11 发布