java簡易爬蟲Crawler


小型簡易爬蟲源碼(java版)



一,介紹:
          >這是個人第一個爬蟲,比較簡單,沒有隊列,廣度優先算法等,用list集合代替了隊列。
       >並且只爬取一個網址上面的圖片,並非將網址中的連接<href>加入隊列,而後下載一個網址一個網址下載其中的圖片。
       >不過,這是前期的,處於摸索階段,後期學完隊列和廣算後,在涉及一點多線程,確定會比想象中的更實用。

二,代碼:

Start_Crawler類:
package com.xhs.crawler;

import java.util.Scanner;

/**
 * @author XHS_12302
 * @version  1.0
 * @date  2017_07_11
 * 
 * 
 * @description 這是個人第一個爬蟲,比較簡單,沒有隊列,廣度優先算法等,用list集合代替了隊列。
 *              並且只爬取一個網址上面的圖片,並非將網址中的連接<href>加入隊列,而後下載一個網址一個網址下載其中的圖片。
 *              不過,這是前期的,處於摸索階段,後期學完隊列和廣算後,在涉及一點多線程,確定會比想象中的更實用
 */
public class Start_Crawler {
	public static void main(String[] args) {
		System.out.println("請輸入網址:");
		
		//獲取用戶要爬取的網址
		Scanner in=new Scanner(System.in);
		String url=in.next();
		
		//經過用戶的輸入創建一個Get_Html的一個g對象
		Get_Html g=new Get_Html(url);
		//調用g中的get()方法模擬請求網站服務器,返回迴應的字符串
		String htmlstr=g.get();
		
		//創建一個Html_analyze對象ha用來分析服務器返回來的字符串
		Html_analyze ha=new Html_analyze(htmlstr);
		
		/*for (String href :ha.analyzeHtmlHref()) {
			System.out.println(href);
		}*/
		
		//調用ha.analyzeHtmlImage()方法將分析出來的圖片地址放進list裏面,傳回來一個圖片地址集合,
		//而後新建下載。
		new Download_pic().Download(ha.analyzeHtmlImage());
		
		System.out.println("program has done!");
		in.close();
	}
}

Get_Html類:

package com.xhs.crawler;

import java.io.BufferedReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

public class Get_Html {
	private String url_path;
	private String htmlstr;
	StringBuffer contentBuffer = new StringBuffer();
	Get_Html(String url){
		this.url_path=url;
	}

	public String get(){
		   FileWriter fw=null;
		try {
			fw=new FileWriter("C:\\Users\\Administrator\\Desktop\\crawler.txt");
			URL url=new URL(url_path);
			URLConnection hc=url.openConnection();
			hc.setConnectTimeout(5000);
			hc.setDoInput(true);
			((HttpURLConnection) hc).setRequestMethod("GET");
			int returnCode=((HttpURLConnection) hc).getResponseCode();
			if(returnCode==200){
				InputStream input=hc.getInputStream();
				
				 InputStreamReader istreamReader = new InputStreamReader(input, "utf-8");  
		         BufferedReader buffStr = new BufferedReader(istreamReader);  
		  
		        String str = null;  
		       while ((str = buffStr.readLine()) != null) 
		          contentBuffer.append(str);
		          htmlstr=contentBuffer.toString();
                  fw.write(htmlstr);
			   input.close();
			   istreamReader.close();
			   buffStr.close();
			   fw.close();
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return htmlstr;
		
	}
	
	
}

Html_analyze類:
package com.xhs.crawler;


import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Html_analyze {
	private String src;
	Html_analyze(String src){
		this.src=src;
	}
	public List<String> analyzeHtmlImage(){
		String regex="http[s]{0,1}://[^\\s]*\\.(jpg|bmp|png)";
		//String sr="http://img5.imgtn.bdimg.com/it/u=1380084653,2448555822&fm=26&gp=0.jpg";
		List<String> listImgUrl=new ArrayList<>();
		Pattern p=Pattern.compile(regex);
		Matcher m=p.matcher(src);
		while(m.find()){
			System.out.println(m.group());
			listImgUrl.add(m.group());
		}
		System.out.println("\n\n總共找到記錄:"+listImgUrl.size()+"\n");
		return listImgUrl;
	}
	public List<String>  analyzeHtmlHref(){
		//分析href標籤   而且加入listHref
		String regex="<a.*?href=\"(.*?)\">";
		List<String> listHref=new ArrayList<>();
		Pattern p=Pattern.compile(regex);
		Matcher m=p.matcher(src);
		while(m.find()){
			listHref.add(m.group());
		}
		return listHref;
	}
}

Download_pic類:
package com.xhs.crawler;

import java.io.File;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import java.util.List;

public class Download_pic {
	public void Download(List<String> listImgSrc) {
		int count = 1;
		for (String url_path : listImgSrc) {
			InputStream in = null;
			FileOutputStream fo = null;
			String imageName = url_path.substring(
					url_path.lastIndexOf("/") + 1, url_path.length());
			try {
				byte[] data = new byte[500];// 1024
				File f = new File(
						"C:\\Users\\Administrator\\Desktop\\crawler\\");
				if (!f.exists()) {
					f.mkdir();
				}
				fo = new FileOutputStream(new File(f.getAbsolutePath() + "\\"
						+ imageName));
				URL url = new URL(url_path);
				HttpURLConnection con = (HttpURLConnection) url
						.openConnection();
				con.setConnectTimeout(5000);
				con.setDoInput(true);
				con.setRequestMethod("GET");
				// con.setRequestProperty("user-agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
				// 設置代理
				int numCode = con.getResponseCode();
				in = con.getInputStream();// int length
				int lengthZ = 0;
				if (numCode == 200) {
					while ((lengthZ = in.read(data)) != -1) {
						fo.write(data, 0, lengthZ); // write(data,0,length);
						fo.flush();
					}
					System.out.println("下載成功:\t" + imageName + "\t剩餘:\t"
							+ (listImgSrc.size() - count));
				} else {
					System.out.println("訪問失敗,返回碼不是200");
				}

			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				System.out.println(imageName + "下載失敗");
			} finally {
				try {
					if (in != null)
						in.close();
					if (fo != null)
						fo.close();
					count++;
				} catch (IOException e) {
					// TODO Auto-generated catch block
					// e.printStackTrace();
					System.out.println("關閉流出現點問題··");
				}
			}

		}
	}

}

三:截圖




這個只是簡易的小東西,不過感受挺好玩的。
       感興趣的朋友能夠本身試試,若是不能知足你要求,
               這兒給你提供一種想法,你能夠利用這種特性爬
                      取csdn博客文章訪問量。^_^



聯繫郵箱:xhsgg12302@outlook.com

                                                                                                                                                                                                                                                                                                                                                                2017_07_11
相關文章
相關標籤/搜索