package Util;import java.io.BufferedInputStream;import java.io.BufferedOutputStream;import java.io.BufferedReader;import java.io.File;import java.io.FileOutputStream;import java.io.FileReader;import java.io.FileWriter;import java.io.IOException;import java.io.InputStreamReader;import java.io.PrintWriter;import java.net.HttpURLConnection;import java.net.URL;import java.util.regex.Matcher;import java.util.regex.Pattern;public class UrlGet { public static void main(String[] args) throws Exception { // TODO Auto-generated method stub //要爬蟲網頁的url String url="https://www.zhihu.com/question/38376393"; //返回儲存有效url的檔案夾名稱 String urlfilename = GetUrl(url); //下載有效url所對應的照片 downPic(urlfilename); System.out.println("Picture download completed"); } //從已經下載下來的有效url中 public static void downPic(String urlfilename) throws Exception { // TODO Auto-generated method stub// URL url = new URL(null); BufferedReader bfr= new BufferedReader(new FileReader(urlfilename)); String url1 = null; int num=0; while((url1=bfr.readLine())!=null){ num++; downPic(bfr, url1,num); } bfr.close(); } /** * 通過擷取的url下載圖片*/ public static void downPic(BufferedReader bfr, String url1 , int num)throws IOException { URL url = new URL(url1); HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); //擷取下載輸入資料流 BufferedInputStream bis= new BufferedInputStream(urlConnection.getInputStream()); //寫出到downPic檔案夾中的流 BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(new File("F:/downPic1/"+num+".jpg"))); int ch=0; byte[] buf = new byte[1024]; //寫入到downPic while((ch=bis.read(buf))!=-1){ bos.write(buf,0,ch); } bos.close(); } //擷取網頁有效UrL public static String GetUrl(String url) throws Exception { // TODO Auto-generated method stub URL u=new URL(url); HttpURLConnection urlConnection = (HttpURLConnection) u.openConnection(); BufferedReader bus= new BufferedReader(new InputStreamReader(urlConnection.getInputStream())); PrintWriter pw = new PrintWriter(new FileWriter("F:/zhihu_pic_url.txt"),true); PrintWriter pw1 = new PrintWriter(new FileWriter("F:/zhihu_content.txt"),true); String regex= "[https|http]+://+[pic]+[A-Za-z0-9.//_%=-]*"; Pattern p = Pattern.compile(regex); String line = null; while((line=bus.readLine())!=null){ Matcher m = p.matcher(line); pw1.println(line); while(m.find()){ pw.println(m.group()); } } bus.close(); pw.close(); pw1.close(); System.out.println("Urlget completed"); String urlfilename="F:/zhihu_pic_url.txt"; return urlfilename; }}
此方法只適用知乎,因為其中的Regex只按照知乎網頁原始碼,不過擷取的網址還是有重複的,只是大小,解析度不同,運行結果如下
這是擷取的有用url,由此得到的照片如下
從上面可以看到下載的照片是有重複的,仔細對比url可以看出,只是照片的大小,解析度不同,所以還可以再進行改進Regex。