爬蟲6:多頁面增量Java爬蟲-sina主頁


  之前寫過很多單頁面python爬蟲,感覺python還是很好用的,這里用java總結一個多頁面的爬蟲,迭代爬取種子頁面的所有鏈接的頁面,全部保存在tmp路徑下。  

  1 序言

  實現這個爬蟲需要兩個數據結構支持,unvisited隊列(priorityqueue:可以適用pagerank等算法計算出url重要度)和visited表(hashset:可以快速查找url是否存在);隊列用於實現寬度優先爬取,visited表用於記錄爬取過的url,不再重復爬取,避免了環。java爬蟲需要的工具包有httpclient和htmlparser1.5,可以在maven repo中查看具體版本的下載。

  1目標網站:新浪  http://www.sina.com.cn/

  2結果截圖:

  下面說說爬蟲的實現,后期源碼會上傳到github中,需要的朋友可以留言:

  二 爬蟲編程 

    1創建種子頁面的url

MyCrawler crawler = new MyCrawler();
crawler.crawling(new String[]{"http://www.sina.com.cn/"});

    2初始化unvisited表為上面的種子url

LinkQueue.addUnvisitedUrl(seeds[i]);

    3最主要的邏輯實現部分:在隊列中取出沒有visit過的url,進行下載,然后加入visited的表,並解析改url頁面上的其它url,把未讀取的加入到unvisited隊列;迭代到隊列為空停止,所以這個url網絡還是很龐大的。注意,這里的頁面下載和頁面解析需要java的工具包實現,下面具體說明下工具包的使用。

    while(!LinkQueue.unVisitedUrlsEmpty()&&LinkQueue.getVisitedUrlNum()<=1000)
        {
            //隊頭URL出隊列
            String visitUrl=(String)LinkQueue.unVisitedUrlDeQueue();
            if(visitUrl==null)
                continue;
            DownLoadFile downLoader=new DownLoadFile();
            //下載網頁
            downLoader.downloadFile(visitUrl);
            //該 url 放入到已訪問的 URL 中
            LinkQueue.addVisitedUrl(visitUrl);
            //提取出下載網頁中的 URL
            
            Set<String> links=HtmlParserTool.extracLinks(visitUrl,filter);
            //新的未訪問的 URL 入隊
            for(String link:links)
            {
                    LinkQueue.addUnvisitedUrl(link);
            }
        }

    4下面html頁面的download工具包

public String downloadFile(String url) {
        String filePath = 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());
                filePath = null;
            }

            /* 4.處理 HTTP 響應內容 */
            byte[] responseBody = getMethod.getResponseBody();// 讀取為字節數組
            // 根據網頁 url 生成保存時的文件名
            filePath = "temp\\"
                    + getFileNameByUrl(url, getMethod.getResponseHeader(
                            "Content-Type").getValue());
            saveToLocal(responseBody, filePath);
        } catch (HttpException e) {
            // 發生致命的異常,可能是協議不對或者返回的內容有問題
            System.out.println("Please check your provided http address!");
            e.printStackTrace();
        } catch (IOException e) {
            // 發生網絡異常
            e.printStackTrace();
        } finally {
            // 釋放連接
            getMethod.releaseConnection();
        }
        return filePath;
    }

 

    5html頁面的解析工具包:

public static Set<String> extracLinks(String url, LinkFilter filter) {

        Set<String> links = new HashSet<String>();
        try {
            Parser parser = new Parser(url);
            parser.setEncoding("gb2312");
            // 過濾 <frame >標簽的 filter,用來提取 frame 標簽里的 src 屬性所表示的鏈接
            NodeFilter frameFilter = new NodeFilter() {
                public boolean accept(Node node) {
                    if (node.getText().startsWith("frame src=")) {
                        return true;
                    } else {
                        return false;
                    }
                }
            };
            // OrFilter 來設置過濾 <a> 標簽,和 <frame> 標簽
            OrFilter linkFilter = new OrFilter(new NodeClassFilter(
                    LinkTag.class), frameFilter);
            // 得到所有經過過濾的標簽
            NodeList list = parser.extractAllNodesThatMatch(linkFilter);
            for (int i = 0; i < list.size(); i++) {
                Node tag = list.elementAt(i);
                if (tag instanceof LinkTag)// <a> 標簽
                {
                    LinkTag link = (LinkTag) tag;
                    String linkUrl = link.getLink();// url
                    if (filter.accept(linkUrl))
                        links.add(linkUrl);
                } else// <frame> 標簽
                {
                    // 提取 frame 里 src 屬性的鏈接如 <frame src="test.html"/>
                    String frame = tag.getText();
                    int start = frame.indexOf("src=");
                    frame = frame.substring(start);
                    int end = frame.indexOf(" ");
                    if (end == -1)
                        end = frame.indexOf(">");
                    String frameUrl = frame.substring(5, end - 1);
                    if (filter.accept(frameUrl))
                        links.add(frameUrl);
                }
            }
        } catch (ParserException e) {
            e.printStackTrace();
        }
        return links;
    }

    6未訪問頁面使用PriorityQueue帶偏好的隊列保存,主要是為了適用於pagerank等算法,有的url忠誠度更高一些;visited表采用hashset實現,注意可以快速查找是否存在;

public class LinkQueue {
    //已訪問的 url 集合
    private static Set visitedUrl = new HashSet();
    //待訪問的 url 集合
    private static Queue unVisitedUrl = new PriorityQueue();

    //獲得URL隊列
    public static Queue getUnVisitedUrl() {
        return unVisitedUrl;
    }
    //添加到訪問過的URL隊列中
    public static void addVisitedUrl(String url) {
        visitedUrl.add(url);
    }
    //移除訪問過的URL
    public static void removeVisitedUrl(String url) {
        visitedUrl.remove(url);
    }
    //未訪問的URL出隊列
    public static Object unVisitedUrlDeQueue() {
        return unVisitedUrl.poll();
    }

    // 保證每個 url 只被訪問一次
    public static void addUnvisitedUrl(String url) {
        if (url != null && !url.trim().equals("")
 && !visitedUrl.contains(url)
                && !unVisitedUrl.contains(url))
            unVisitedUrl.add(url);
    }
    //獲得已經訪問的URL數目
    public static int getVisitedUrlNum() {
        return visitedUrl.size();
    }
    //判斷未訪問的URL隊列中是否為空
    public static boolean unVisitedUrlsEmpty() {
        return unVisitedUrl.isEmpty();
    }

}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM