因为是实例所以方法和类的名都随意的一些: class CheckData { // 获取img标签正则 private static final String IMGURL_REG = "<img.*src=(.*?)[^>]*?>"; // 获取src路径的正则 private static final String IMGSRC_REG = "[a-zA-z]+://[^\\s]*"; public static void getData(String requestUrl) throws IOException { HttpURLConnection connection = null;//url连接,和定义请求方式 InputStream inputStream = null;//输入流 InputStreamReader inputStreamReader = null;//输入字符流,用于获取到网页的输入流后,将输入流转换成字符流。 BufferedReader bufferedReader = null;//用于缓存字符流 StringBuffer buffer = null;//将分割出来的字符流拼接 //建立get请求 URL url = new URL(requestUrl); connection = (HttpURLConnection) url.openConnection(); connection.setDoInput(true); connection.setRequestMethod("GET"); //获取输入流 inputStream = connection.getInputStream();//获取连接中的输入流 inputStreamReader = new InputStreamReader(inputStream, "utf-8");//将字符流转成utf-8的字符流 bufferedReader = new BufferedReader(inputStreamReader);//将字符流储存起来 buffer = new StringBuffer(); String str = null; while ((str = bufferedReader.readLine()) != null) {//获取存储字符流的 buffer.append(str); } //todo 以上则为拉取数据的代码,要拉取网页中的图片则需要加上一下代码 //拉取网页中带有<img>标签的数据并保存 Matcher matcher = Pattern.compile(IMGURL_REG).matcher(buffer.toString()); List<String> listimgurl = new ArrayList<String>(); while (matcher.find()) { listimgurl.add(matcher.group()); } List<String> imgs = new ArrayList<>(); //拉取网页中带有<img>标签的数据并保存 for (String img : listimgurl) { Matcher matcher1 = Pattern.compile(IMGSRC_REG).matcher(img); while (matcher1.find()) { imgs.add(matcher1.group()); } } System.out.println(imgs); }
调用实例:
String data = null; try { String ser="https://fabiaoqing.com/biaoqing"; CheckData.getData(ser); } catch (IOException e) { System.out.println("出错"); }