groovy爬蟲實例——歷史上的今天

最近作了一個歷史上今天的爬蟲程序,跟歷史天氣數據源一致,數據量比較小,幾十秒就爬完了。中間遇到一些問題,一塊兒分享出來供你們參考。本項目源碼和相關數據已經上傳到了github,有興趣的朋友能夠去看看,會不按期更新。java

git傳送門git

  1. get請求發送sql語句不能過長:我是作爬蟲裏面把sql拼好,發送到數據庫存儲服務上,以前一直用的get請求,因爲此次內容較多,超過了最大長度限制,致使報錯。故改成post請求,且兼容了get請求方式。github

  2. 不明確的數據類型:某個年份的某一天事件不惟一的話,json格式的value是array,若是惟一則是一個json。在處理這個數據的時候纔去了正則匹配。總結起來,在提取相關接口數據的時候,正則最好用。sql

  3. 拼接月份的時候有點複雜,直接寫了一個省事兒的方法,若是各位有簡單好用的,望不吝賜教。數據庫

static void main(String[] args) {
        DEFAULT_CHARSET = GBK;
 
        for (int i in 1..12) {
            for (int j in 1..31) {
                if (i == 2 && (j == 30 || j == 31)) continue
                if ((i in [4, 6, 9, 11]) && j == 31) continue
                def month = i > 9 ? i + EMPTY : "0" + i;
                def day = j > 9 ? j + EMPTY : "0" + j;
                def date = month + "-" + day
                getInfo(date)
            }
        }
        testOver()
    }
    static getInfo(String date) {
        def url = "http://tools.***.com/his/" + date.replace("-", EMPTY) + "_c.js"
        def all = FanRequest.isGet()
                .setUri(url)
                .getResponse()
                .getString("content")
                .substring(8)
                .replace(";", EMPTY)
                .replaceAll("(&nbsp)+", EMPTY)
                .replaceAll("\\t", EMPTY)
                .replace("##", EMPTY)
                .replaceAll(SPACE_1, EMPTY)
        def json = JSONObject.fromObject(all)
        def keys = json.keySet()
        keys.each { key ->
            def s = json.get(key).toString()
            def all1 = Regex.regexAll(s, "\\{\"title.+?\\}")
            for (int i in 0..all1.size() - 1) {
                def info = all1.get(i)
                def inf = JSONObject.fromObject(info.toString())
                def title = inf.getString("title")
                def keyword = inf.getString("keyword")
                def content = inf.getString("content")
                def alt = inf.getString("alt")
                String sql = "INSERT INTO today_histroy (date,title,keyword,content,alt) VALUES (\"%s\",\"%s\",\"%s\",\"%s\",\"%s\");"
                sql = String.format(sql, key + "-" + date, title, keyword, content.replace("  ", EMPTY), alt)
                MySqlTest.sendWork(sql)
            }
        }
    }

技術類文章精選

非技術文章精選

大咖風采

點擊查看公衆號地圖

相關文章
相關標籤/搜索