Java爬蟲初體驗

年關將近,工做上該完成的都差很少了,上午閒着就接觸學習了一下爬蟲,抽空還把正則表達式複習了,Java的Regex和JS上仍是有區別的,JS上的"\w"Java得寫成"\\w",由於Java會對字符串中的"\"作轉義,還有JS中"\S\s"的寫法(指任意多的任意字符),Java能夠寫成".*"css

博主剛接觸爬蟲,參考了許多博客和問答貼,先寫個爬蟲的Overview讓朋友們對其有些印象,以後咱們再展現代碼.
html

 

網絡爬蟲的基本原理:java

網絡爬蟲的基本工做流程以下:node

    1.首先選取一部分精心挑選的種子URL;正則表達式

    2.將這些URL放入待抓取URL隊列;數據庫

    3.從待抓取URL隊列中取出待抓取在URL,解析DNS,而且獲得主機的ip,並將URL對應的網頁下載下來,存儲進已下載網頁庫中。此外,將這些URL放進已抓取URL隊列。apache

    4.分析已抓取URL隊列中的URL,分析其中的其餘URL,而且將URL放入待抓取URL隊列,從而進入下一個循環。編程

 

網絡爬蟲的抓取策略有:深度優先遍歷,廣度優先遍歷(是否是想到了圖的深度和廣度優先遍歷?),Partial PageRank,OPIC策略,大站優先等;
數組

博主採用的是實現起來比較簡單的廣度優先遍歷,即獲取一個頁面中全部的URL後,將之塞進URL隊列,因而循環條件就是該隊列非空.網絡

網絡爬蟲(HelloWorld版)

入口類:

package com.example.spiderman.page;

/**
* @author YHW * @ClassName: MyCrawler * @Description: */ import com.example.spiderman.link.LinkFilter; import com.example.spiderman.link.Links; import com.example.spiderman.page.Page; import com.example.spiderman.page.PageParserTool; import com.example.spiderman.page.RequestAndResponseTool; import com.example.spiderman.utils.FileTool; import com.example.spiderman.utils.RegexRule; import org.jsoup.select.Elements; import java.util.Set; public class MyCrawler { /** * 使用種子初始化 URL 隊列 * * @param seeds 種子 URL * @return */ private void initCrawlerWithSeeds(String[] seeds) { for (int i = 0; i < seeds.length; i++){ Links.addUnvisitedUrlQueue(seeds[i]); } } /** * 抓取過程 * * @param seeds * @return */ public void crawling(String[] seeds) { //初始化 URL 隊列 initCrawlerWithSeeds(seeds); //定義過濾器,提取以 變量url 開頭的連接 LinkFilter filter = new LinkFilter() { @Override public boolean accept(String url) { if (url.startsWith("https://www.cnblogs.com/Joey44/")) return true; else return false; } }; //循環條件:待抓取的連接不空且抓取的網頁很少於 1000 while (!Links.unVisitedUrlQueueIsEmpty() && Links.getVisitedUrlNum() <= 1000) { //先從待訪問的序列中取出第一個; String visitUrl = (String) Links.removeHeadOfUnVisitedUrlQueue(); if (visitUrl == null){ continue; } //根據URL獲得page; Page page = RequestAndResponseTool.sendRequstAndGetResponse(visitUrl); //對page進行處理: 訪問DOM的某個標籤 Elements es = PageParserTool.select(page,"a"); if(!es.isEmpty()){ System.out.println("下面將打印全部a標籤: "); System.out.println(es); } //將保存文件 FileTool.saveToLocal(page); //將已經訪問過的連接放入已訪問的連接中; Links.addVisitedUrlSet(visitUrl); //獲得超連接 Set<String> links = PageParserTool.getLinks(page,"a"); for (String link : links) {
          //遍歷連接集合,並用正則過濾出須要的URL,再存入URL隊列中去,博主這裏篩出了全部博主博客相關的URL RegexRule regexRule
= new RegexRule(); regexRule.addPositive("http.*/Joey44/.*html.*");
          if(regexRule.satisfy(link)){ Links.addUnvisitedUrlQueue(link); System.out.println("新增爬取路徑: " + link); } } } } //main 方法入口 public static void main(String[] args) { MyCrawler crawler = new MyCrawler(); crawler.crawling(new String[]{"https://www.cnblogs.com/Joey44/"}); } }

 

網絡編程天然少不了Http訪問,直接用apache的httpclient包就行:

package com.example.spiderman.page;

/**
 * @author YHW
 * @ClassName: RequestAndResponseTool
 * @Description:
 */

import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;

import java.io.IOException;

public class RequestAndResponseTool {


    public static Page  sendRequstAndGetResponse(String url) {
        Page page = null;
        // 1.生成 HttpClinet 對象並設置參數
        HttpClient httpClient = new HttpClient();
        // 設置 HTTP 鏈接超時 5s
        httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
        // 2.生成 GetMethod 對象並設置參數
        GetMethod getMethod = new GetMethod(url);
        // 設置 get 請求超時 5s
        getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 5000);
        // 設置請求重試處理
        getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
        // 3.執行 HTTP GET 請求
        try {
            int statusCode = httpClient.executeMethod(getMethod);
            // 判斷訪問的狀態碼
            if (statusCode != HttpStatus.SC_OK) {
                System.err.println("Method failed: " + getMethod.getStatusLine());
            }
            // 4.處理 HTTP 響應內容
            byte[] responseBody = getMethod.getResponseBody();// 讀取爲字節 數組
            String contentType = getMethod.getResponseHeader("Content-Type").getValue(); // 獲得當前返回類型
            page = new Page(responseBody,url,contentType); //封裝成爲頁面
        } catch (HttpException e) {
            // 發生致命的異常,多是協議不對或者返回的內容有問題
            System.out.println("Please check your provided http address!");
            e.printStackTrace();
        } catch (IOException e) {
            // 發生網絡異常
            e.printStackTrace();
        } finally {
            // 釋放鏈接
            getMethod.releaseConnection();
        }
        return page;
    }
}

 

別忘了導入Maven依賴:

<!-- https://mvnrepository.com/artifact/commons-httpclient/commons-httpclient -->
        <dependency>
            <groupId>commons-httpclient</groupId>
            <artifactId>commons-httpclient</artifactId>
            <version>3.0</version>
        </dependency>

 

接下來要讓咱們的程序能夠存儲頁面,新建Page實體類: 

package com.example.spiderman.page;

/**
 * @author YHW
 * @ClassName: Page
 * @Description:
 */
import com.example.spiderman.utils.CharsetDetector;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import java.io.UnsupportedEncodingException;

/*
 * page
 *   1: 保存獲取到的響應的相關內容;
 * */
public class Page {

    private byte[] content ;
    private String html ;  //網頁源碼字符串
    private Document doc  ;//網頁Dom文檔
    private String charset ;//字符編碼
    private String url ;//url路徑
    private String contentType ;// 內容類型


    public Page(byte[] content , String url , String contentType){
        this.content = content ;
        this.url = url ;
        this.contentType = contentType ;
    }

    public String getCharset() {
        return charset;
    }
    public String getUrl(){return url ;}
    public String getContentType(){ return contentType ;}
    public byte[] getContent(){ return content ;}

    /**
     * 返回網頁的源碼字符串
     *
     * @return 網頁的源碼字符串
     */
    public String getHtml() {
        if (html != null) {
            return html;
        }
        if (content == null) {
            return null;
        }
        if(charset==null){
            charset = CharsetDetector.guessEncoding(content); // 根據內容來猜想 字符編碼
        }
        try {
            this.html = new String(content, charset);
            return html;
        } catch (UnsupportedEncodingException ex) {
            ex.printStackTrace();
            return null;
        }
    }

    /*
     *  獲得文檔
     * */
    public Document getDoc(){
        if (doc != null) {
            return doc;
        }
        try {
            this.doc = Jsoup.parse(getHtml(), url);
            return doc;
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }
    }


}

 

而後要有頁面的解析功能類:

package com.example.spiderman.page;

/**
 * @author YHW
 * @ClassName: PageParserTool
 * @Description:
 */
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

public class PageParserTool {


    /* 經過選擇器來選取頁面的 */
    public static Elements select(Page page , String cssSelector) {
        return page.getDoc().select(cssSelector);
    }

    /*
     *  經過css選擇器來獲得指定元素;
     *
     *  */
    public static Element select(Page page , String cssSelector, int index) {
        Elements eles = select(page , cssSelector);
        int realIndex = index;
        if (index < 0) {
            realIndex = eles.size() + index;
        }
        return eles.get(realIndex);
    }


    /**
     * 獲取知足選擇器的元素中的連接 選擇器cssSelector必須定位到具體的超連接
     * 例如咱們想抽取id爲content的div中的全部超連接,這裏
     * 就要將cssSelector定義爲div[id=content] a
     *  放入set 中 防止重複;
     * @param cssSelector
     * @return
     */
    public static  Set<String> getLinks(Page page ,String cssSelector) {
        Set<String> links  = new HashSet<String>() ;
        Elements es = select(page , cssSelector);
        Iterator iterator  = es.iterator();
        while(iterator.hasNext()) {
            Element element = (Element) iterator.next();
            if ( element.hasAttr("href") ) {
                links.add(element.attr("abs:href"));
            }else if( element.hasAttr("src") ){
                links.add(element.attr("abs:src"));
            }
        }
        return links;
    }



    /**
     * 獲取網頁中知足指定css選擇器的全部元素的指定屬性的集合
     * 例如經過getAttrs("img[src]","abs:src")可獲取網頁中全部圖片的連接
     * @param cssSelector
     * @param attrName
     * @return
     */
    public static ArrayList<String> getAttrs(Page page , String cssSelector, String attrName) {
        ArrayList<String> result = new ArrayList<String>();
        Elements eles = select(page ,cssSelector);
        for (Element ele : eles) {
            if (ele.hasAttr(attrName)) {
                result.add(ele.attr(attrName));
            }
        }
        return result;
    }
}

 

別忘了導入Maven依賴:

<!-- https://mvnrepository.com/artifact/org.jsoup/jsoup -->
        <dependency>
            <groupId>org.jsoup</groupId>
            <artifactId>jsoup</artifactId>
            <version>1.11.3</version>
        </dependency>

 

最後就是額外須要的一些工具類:正則匹配工具,頁面編碼偵測和存儲頁面工具

package com.example.spiderman.utils;

/**
 * @author YHW
 * @ClassName: RegexRule
 * @Description:
 */
import java.util.ArrayList;
import java.util.regex.Pattern;

public class RegexRule {

    public RegexRule(){

    }
    public RegexRule(String rule){
        addRule(rule);
    }

    public RegexRule(ArrayList<String> rules){
        for (String rule : rules) {
            addRule(rule);
        }
    }

    public boolean isEmpty(){
        return positive.isEmpty();
    }

    private ArrayList<String> positive = new ArrayList<String>();
    private ArrayList<String> negative = new ArrayList<String>();



    /**
     * 添加一個正則規則 正則規則有兩種,正正則和反正則
     * URL符合正則規則須要知足下面條件: 1.至少能匹配一條正正則 2.不能和任何反正則匹配
     * 正正則示例:+a.*c是一條正正則,正則的內容爲a.*c,起始加號表示正正則
     * 反正則示例:-a.*c時一條反正則,正則的內容爲a.*c,起始減號表示反正則
     * 若是一個規則的起始字符不爲加號且不爲減號,則該正則爲正正則,正則的內容爲自身
     * 例如a.*c是一條正正則,正則的內容爲a.*c
     * @param rule 正則規則
     * @return 自身
     */
    public RegexRule addRule(String rule) {
        if (rule.length() == 0) {
            return this;
        }
        char pn = rule.charAt(0);
        String realrule = rule.substring(1);
        if (pn == '+') {
            addPositive(realrule);
        } else if (pn == '-') {
            addNegative(realrule);
        } else {
            addPositive(rule);
        }
        return this;
    }



    /**
     * 添加一個正正則規則
     * @param positiveregex
     * @return 自身
     */
    public RegexRule addPositive(String positiveregex) {
        positive.add(positiveregex);
        return this;
    }


    /**
     * 添加一個反正則規則
     * @param negativeregex
     * @return 自身
     */
    public RegexRule addNegative(String negativeregex) {
        negative.add(negativeregex);
        return this;
    }


    /**
     * 判斷輸入字符串是否符合正則規則
     * @param str 輸入的字符串
     * @return 輸入字符串是否符合正則規則
     */
    public boolean satisfy(String str) {

        int state = 0;
        for (String nregex : negative) {
            if (Pattern.matches(nregex, str)) {
                return false;
            }
        }

        int count = 0;
        for (String pregex : positive) {
            if (Pattern.matches(pregex, str)) {
                count++;
            }
        }
        if (count == 0) {
            return false;
        } else {
            return true;
        }

    }
}
package com.example.spiderman.utils;

/**
 * @author YHW
 * @ClassName: CharsetDetector
 * @Description:
 */


import org.mozilla.universalchardet.UniversalDetector;

import java.io.UnsupportedEncodingException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 字符集自動檢測
 **/
public class CharsetDetector {

    //從Nutch借鑑的網頁編碼檢測代碼
    private static final int CHUNK_SIZE = 2000;

    private static Pattern metaPattern = Pattern.compile(
            "<meta\\s+([^>]*http-equiv=(\"|')?content-type(\"|')?[^>]*)>",
            Pattern.CASE_INSENSITIVE);
    private static Pattern charsetPattern = Pattern.compile(
            "charset=\\s*([a-z][_\\-0-9a-z]*)", Pattern.CASE_INSENSITIVE);
    private static Pattern charsetPatternHTML5 = Pattern.compile(
            "<meta\\s+charset\\s*=\\s*[\"']?([a-z][_\\-0-9a-z]*)[^>]*>",
            Pattern.CASE_INSENSITIVE);

    //從Nutch借鑑的網頁編碼檢測代碼
    private static String guessEncodingByNutch(byte[] content) {
        int length = Math.min(content.length, CHUNK_SIZE);

        String str = "";
        try {
            str = new String(content, "ascii");
        } catch (UnsupportedEncodingException e) {
            return null;
        }

        Matcher metaMatcher = metaPattern.matcher(str);
        String encoding = null;
        if (metaMatcher.find()) {
            Matcher charsetMatcher = charsetPattern.matcher(metaMatcher.group(1));
            if (charsetMatcher.find()) {
                encoding = new String(charsetMatcher.group(1));
            }
        }
        if (encoding == null) {
            metaMatcher = charsetPatternHTML5.matcher(str);
            if (metaMatcher.find()) {
                encoding = new String(metaMatcher.group(1));
            }
        }
        if (encoding == null) {
            if (length >= 3 && content[0] == (byte) 0xEF
                    && content[1] == (byte) 0xBB && content[2] == (byte) 0xBF) {
                encoding = "UTF-8";
            } else if (length >= 2) {
                if (content[0] == (byte) 0xFF && content[1] == (byte) 0xFE) {
                    encoding = "UTF-16LE";
                } else if (content[0] == (byte) 0xFE
                        && content[1] == (byte) 0xFF) {
                    encoding = "UTF-16BE";
                }
            }
        }

        return encoding;
    }

    /**
     * 根據字節數組,猜想可能的字符集,若是檢測失敗,返回utf-8
     *
     * @param bytes 待檢測的字節數組
     * @return 可能的字符集,若是檢測失敗,返回utf-8
     */
    public static String guessEncodingByMozilla(byte[] bytes) {
        String DEFAULT_ENCODING = "UTF-8";
        UniversalDetector detector = new UniversalDetector(null);
        detector.handleData(bytes, 0, bytes.length);
        detector.dataEnd();
        String encoding = detector.getDetectedCharset();
        detector.reset();
        if (encoding == null) {
            encoding = DEFAULT_ENCODING;
        }
        return encoding;
    }

    /**
     * 根據字節數組,猜想可能的字符集,若是檢測失敗,返回utf-8
     * @param content 待檢測的字節數組
     * @return 可能的字符集,若是檢測失敗,返回utf-8
     */
    public static String guessEncoding(byte[] content) {
        String encoding;
        try {
            encoding = guessEncodingByNutch(content);
        } catch (Exception ex) {
            return guessEncodingByMozilla(content);
        }

        if (encoding == null) {
            encoding = guessEncodingByMozilla(content);
            return encoding;
        } else {
            return encoding;
        }
    }
}
package com.example.spiderman.utils;

/**
 * @author YHW
 * @ClassName: FileTool
 * @Description:
 */
import com.example.spiderman.page.Page;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

/*  本類主要是 下載那些已經訪問過的文件*/
public class FileTool {

    private static String dirPath;


    /**
     * getMethod.getResponseHeader("Content-Type").getValue()
     * 根據 URL 和網頁類型生成須要保存的網頁的文件名,去除 URL 中的非文件名字符
     */
    private static String getFileNameByUrl(String url, String contentType) {
        //去除 http://
        url = url.substring(7);
        //text/html 類型
        if (contentType.indexOf("html") != -1) {
            url = url.replaceAll("[\\?/:*|<>\"]", "_") + ".html";
            return url;
        }
        //如 application/pdf 類型
        else {
            return url.replaceAll("[\\?/:*|<>\"]", "_") + "." +
                    contentType.substring(contentType.lastIndexOf("/") + 1);
        }
    }

    /*
     *  生成目錄
     * */
    private static void mkdir() {
        if (dirPath == null) {
            dirPath = Class.class.getClass().getResource("/").getPath() + "temp\\";
        }
        File fileDir = new File(dirPath);
        if (!fileDir.exists()) {
            fileDir.mkdir();
        }
    }

    /**
     * 保存網頁字節數組到本地文件,filePath 爲要保存的文件的相對地址
     */

    public static void saveToLocal(Page page) {
        mkdir();
        String fileName =  getFileNameByUrl(page.getUrl(), page.getContentType()) ;
        String filePath = dirPath + fileName ;
        byte[] data = page.getContent();
        try {
            //Files.lines(Paths.get("D:\\jd.txt"), StandardCharsets.UTF_8).forEach(System.out::println);
            DataOutputStream out = new DataOutputStream(new FileOutputStream(new File(filePath)));
            for (int i = 0; i < data.length; i++) {
                out.write(data[i]);
            }
            out.flush();
            out.close();
            System.out.println("文件:"+ fileName + "已經被存儲在"+ filePath  );
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

爲了拓展性,增長一個LinkFilter接口:

package com.example.spiderman.link;

/**
 * @author YHW
 * @ClassName: LinkFilter
 * @Description:
 */
public interface LinkFilter {
    public boolean accept(String url);
}

總體項目結構:

運行結果(部分):

 

 

網絡爬蟲的Helloworld版本就完成了,固然還有許多能夠改進的地方,例如多線程訪問URL隊列;在咱們獲取網站源碼以後,就能夠利用解析工具獲取該頁面任意的元素標籤,再進行正則表達式過濾出咱們想要的數據了,能夠將數據存儲到數據庫裏,還能夠根據須要使用分佈式爬蟲提升爬取速率.

 

參考文章:

https://www.cnblogs.com/wawlian/archive/2012/06/18/2553061.html

http://www.javashuo.com/article/p-pagywvea-cm.html

相關文章
相關標籤/搜索