Java網頁資料擷取器[中篇-資料存放區]

來源:互聯網
上載者:User

上一篇地址:http://blog.csdn.net/zxciop110/article/details/8544649

本期概述

上期我們學習了html頁面的資料擷取,為了方便我們今後來調用收集到的資料,首先我們需要學習下如何將這些採集到的資料存放區起來(MySql資料庫).

資料擷取頁面
2011-2012賽季英超球隊戰績

 

關於Java操作MySql

在使用java 操作MySql資料庫之前 我們需要在專案檔中匯入 一個jar包(mysql-connector-java-5.1.18-bin)

可以在MySql官網下載
Connector/J 5.1.18

第一次使用MySql?   請看
java串連MYSQL      

如何在java項目中匯入jar包?

請看這個
Eclipse下如何匯入jar包

關於MySql資料庫 

如果是初學者 想使用MySql資料庫的話 可以去這裡
XAMPP中文官網  下載 XAMPP 套裝.

XAMPP(Apache+MySQL+PHP+PERL)是一個功能強大的建 XAMPP 軟體站整合軟體包, 而且一鍵式安裝, 無需修改設定檔,非常好用.  

 

好了, 需要準備的事宜都完成了,我們開始寫代碼.

開啟MySql資料庫,建立資料庫 和表 (拷貝如下代碼 到mysql裡直接執行即可).

建立MySql資料庫#建立資料庫  htmldatacollectionCREATE DATABASE htmldatacollection; #在建立表之前 我們需要使用資料庫htmldatacollectionuse htmldatacollection;    #在資料庫裡 建立一個表 Premiership 用於儲存我們收集到的資料#這裡為了方便 所有欄位 全部是字串格式CREATE TABLE Premiership(Date varchar(15),HomeTeam varchar(20),AwayTeam varchar(20),Result varchar(20) )

建立好後,我們來看看資料庫結構.

主程式碼
資料庫弄好了,我們開始實施java代碼, 這裡簡單介紹下各個類以及類所包含的方法.

DataStorage類 以及包含的 dataStore()方法 用於資料收集和儲存 

DataStorage類import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.net.URL;/** * DataStorage類 用於資料的收集和儲存 * @author SoFlash - 部落格園  http://www.cnblogs.com/longwu */public class DataStorage {    public void dataStore() {        // 首先用一個字串 來裝載網頁連結        String strUrl = "http://www.footballresults.org/league.php?all=1&league=EngPrem";                String sqlLeagues = "";        try {            // 建立一個url對象來指向 該網站連結 括弧裡()裝載的是該網站連結的路徑            // 更多可以看看 http://wenku.baidu.com/view/8186caf4f61fb7360b4c6547.html            URL url = new URL(strUrl);            // InputStreamReader 是一個輸入資料流讀取器 用於將讀取的位元組轉換成字元            // 更多可以看看 http://blog.sina.com.cn/s/blog_44a05959010004il.html            InputStreamReader isr = new InputStreamReader(url.openStream(),                    "utf-8"); // 統一使用utf-8 編碼模式            // 使用 BufferedReader 來讀取 InputStreamReader 轉換成的字元            BufferedReader br = new BufferedReader(isr);            String strRead = ""; // new 一個字串來裝載 BufferedReader 讀取到的內容            // 定義3個正則 用於擷取我們需要的資料            String regularDate = "(\\d{1,2}\\.\\d{1,2}\\.\\d{4})";            String regularTwoTeam = ">[^<>]*</a>";            String regularResult = ">(\\d{1,2}-\\d{1,2})</TD>";            //建立 GroupMethod類的對象 gMethod 方便後期調用其類裡的 regularGroup方法            GroupMethod gMethod = new GroupMethod();            //建立DataStructure資料結構 類的對象   用於資料下面的資料存放區            DataStructure ds = new DataStructure();            //建立MySql類的對象 用於執行MySql語句            MySql ms = new MySql();            int i = 0; // 定義一個i來記錄迴圈次數 即收集到的球隊比賽結果數            int index = 0; // 定義一個索引 用於擷取分離 2個球隊的資料 因為2個球隊正則是相同的            // 開始讀取資料 如果讀到的資料不為空白 則往裡面讀            while ((strRead = br.readLine()) != null) {                /**                 * 用於捕獲日期資料                 */                String strGet = gMethod.regularGroup(regularDate, strRead);                // 如果捕獲到了合格 日期資料 則列印出來                                if (!strGet.equals("")) {                    //System.out.println("Date:" + strGet);                    //將收集到的日期存在資料結構裡                    ds.date = strGet;                    // 這裡索引+1 是用於擷取後期的球隊資料                    ++index; // 因為在html頁面裡 原始碼裡 球隊資料是在剛好在日期之後                }                /**                 * 用於擷取2個球隊的資料                 */                strGet = gMethod.regularGroup(regularTwoTeam, strRead);                if (!strGet.equals("") && index == 1) { // 索引為1的是主隊資料                    // 通過subtring方法 分離出 主隊資料                    strGet = strGet.substring(1, strGet.indexOf("</a>"));                    //System.out.println("HomeTeam:" + strGet); // 列印出主隊                    //將收集到的主隊名稱 存到 資料結構裡                    ds.homeTeam = strGet;                    index++; // 索引+1之後 為2了                    // 通過subtring方法 分離出 客隊                } else if (!strGet.equals("") && index == 2) { // 這裡索引為2的是客隊資料                    strGet = strGet.substring(1, strGet.indexOf("</a>"));                    //System.out.println("AwayTeam:" + strGet); // 列印出客隊                    //將收集到的客隊名稱 存到資料結構裡                    ds.awayTeam = strGet;                    index = 0;  //收集完客隊名稱後 需要將索引還原 用於收集下一條資料的主隊名稱                }                /**                 * 用於擷取比賽結果                 */                strGet = gMethod.regularGroup(regularResult, strRead);                if (!strGet.equals("")) {                    // 這裡同樣用到了substring方法 來剔除'<' 和 "</TD>" 標籤 來擷取我們想要的比賽結果                    strGet = strGet.substring(1, strGet.indexOf("</TD>"));                    //System.out.println("Result:" + strGet);                    ds.result = strGet; //將收集到的比賽結果存到資料結構裡                    //System.out.println();                                        //MySql插入語句                    sqlLeagues = "INSERT INTO Premiership values(\""                            + ds.date + "\"," + "\"" + ds.homeTeam                            + "\"," + "\"" + ds.awayTeam + "\","+ "\"" + ds.result + "\")";                    //調用MySql類的datatoMySql()方法 來執行 MySql插入語句                    ms.datatoMySql(sqlLeagues);                    i++; //每插入完一條記錄 i+1;                    System.out.println("第"+i+"條資料插入成功");                }            }            // 當讀完資料後 記得關閉 BufferReader            br.close();            //System.out.println("共收集到" + i + "條比賽記錄");// 列印出迴圈次數            //當資料存放區完成後 列印出 收集球隊記錄數            System.out.println("資料存放區完畢,共插入資料庫"+i+"條記錄");        } catch (IOException e) {            // 如果出錯 拋出異常            e.printStackTrace();        }    }}

DataStructure類  簡單資料結構 裡麵包含了相應的欄位  用於將收集的資料臨時性儲存

DataStructure 類/** * DataStructure 類 一個簡單的資料結構 * @author SoFlash - 部落格園  http://www.cnblogs.com/longwu */public class DataStructure {     //定義資料欄位    public String homeTeam;    public String awayTeam;    public String date;    public String result;}

GroupMethod類 以及包含的  regularGroup()方法 用於正則匹配html 原始碼上的資料

GroupMethod 類import java.util.regex.Matcher;import java.util.regex.Pattern;/** * GroupMethod 類 用於匹配和抓取 html頁面的資料 * @author SoFlash - 部落格園  http://www.cnblogs.com/longwu */public class GroupMethod {    // 傳入2個字串參數 一個是pattern(我們使用的正則) 另一個matcher是html原始碼    public String regularGroup(String pattern, String matcher) {        Pattern p = Pattern.compile(pattern, Pattern.CASE_INSENSITIVE);        Matcher m = p.matcher(matcher);        if (m.find()) { // 如果讀到            return m.group();// 返回捕獲的資料        } else {            return ""; // 否則返回一個空值        }    }}

MySql類 以及包含的 datatoMySql() 方法 用於執行SQL插入語句 將臨時儲存在資料結構裡的資料 插入到MySql資料庫中

MySql類import java.sql.Connection;import java.sql.DriverManager;import java.sql.SQLException;import java.sql.Statement;/** * MySql類用於實施MySql資料庫操作 * @author SoFlash - 部落格園  http://www.cnblogs.com/longwu */public class MySql {      //定義MySql驅動,資料庫地址,資料庫使用者名稱 密碼, 執行語句和資料庫連接      public String driver = "com.mysql.jdbc.Driver";    public String url = "jdbc:mysql://127.0.0.1:3306/htmldatacollection";    public String user = "root";    public String password = "root";    public Statement stmt = null;    public Connection conn = null;        //建立一個插入資料的方法    public void datatoMySql(String insertSQl) {        try {            try {                Class.forName(driver).newInstance();            } catch (Exception e) {                System.out.println("Unable to find the local driver");                e.printStackTrace();            }            //建立串連            conn = DriverManager.getConnection(url, user, password);            //建立一個 Statement 對象來將 SQL 陳述式發送到資料庫            stmt = conn.createStatement();        } catch (SQLException e) {            e.printStackTrace();        }        try {            //執行SQL 插入語句            stmt.executeUpdate(insertSQl);        } catch (SQLException e) {            e.printStackTrace();        }        try {            //執行完 停止執行語句            stmt.close();            //執行完關閉資料庫連接            conn.close();        } catch (SQLException e) {            e.printStackTrace();        }    }}

Main 主函數 用於資料輸出

Main 主函數/** * Main 主函數 用於資料輸出 * @author SoFlash - 部落格園  http://www.cnblogs.com/longwu */public class Main {    public static void main(String[] args) {         //在主函數裡調用DataStorage類裡的dataStore()方法        DataStorage ds = new DataStorage();        ds.dataStore();    }}

運行查看
好了,下面我們來執行下 看看結果.

資料擷取頁面
2011-2012賽季英超球隊戰績

Html頁面-初始階段

 

MySql資料庫-初始階段

Html頁面-結束階段

 

MySql資料庫-結束階段

一共收集到 189條記錄

MySql資料庫顯示 189 行資料

 

這樣,我們2011-2012英超聯盟賽季的比賽戰績就全部收集並存到MySql資料庫裡了.  :)

源碼地址

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.