使用PHP 的 curl 爬取 青果教務系統 課表

近段需要寫關於爬取課表的功能,現在完成了,來總結一下,說說自己踩過的坑。希望能幫到大家。

1. 分析

首先我們要了解 Http Cookie 的作用(可參考HTTP cookies 詳解),簡單來說就是維持一個會話,這樣我們就能在登陸一個網頁後,就能進入這個網頁需要登陸的界面。

現在我們需要模擬登陸青果教務系統,就也需要先獲取服務器給我們的cookie,然後用這個cookie值去獲取驗證碼登陸,獲取我們想要的內容。要注意的是有的網站對錶頭信息也是有驗證的,我們需要在請求中添加表頭信息。

總結起來就三部,首先獲取登錄界面的驗證碼並存儲Cookie,然後通過cookie來模擬登陸,最後進入教務系統取想要的東西。

現在我們需要去留意的內容,各個請求的連接、header、和發送的數據

2. 查看請求

首先我們查看首頁,我們發現登錄並不在首頁上,需要點擊用戶登錄後纔算進入了登錄界面。
這裏寫圖片描述

這裏寫圖片描述

然後我們查看登錄界面的請求。我們就是需要圖中的Cookie 來登錄,
這裏寫圖片描述

在看驗證碼的請求,發現其中你的Cookie是一樣的,所以,我們直接獲取驗證碼的Cookie保存就行,不管登界面。
這裏寫圖片描述

我們在看登錄的請求,請求類型爲POST,還是原來的cookie,但是我們發現傳送的數據竟然那麼多,其實,比多請求幾次就會發現,其實有幾個的值是永遠不會變的,我們下面接着分析。
這裏寫圖片描述
這裏寫圖片描述

查看錶單登錄結構,發現剛纔的提交數據都是隱藏的標籤,並且都是大部分都是固定值,只有兩個是我在輸入密碼或驗證碼時會一直變動,其實這兩個就是密碼和驗證碼,只是進行了特殊處理,這個網頁引入了一個 md5.js 文件(上面第二張圖中可以看到),加密就是通過這個文件進行的。
這裏寫圖片描述

我們尋找加密部分的代碼,在頁面的某一部分,我們發現了加密的代碼,我們在模擬登陸時就可以使用這部分處理了。
這裏寫圖片描述

當我們登陸成功後我們課表的請求。OK,我們的心思收集工作完成了。下面開始編碼吧。
這裏寫圖片描述

3. 獲取驗證碼和Cookie

首先我們需要一個界面來模擬登陸,我寫了一個簡單的html form登錄,需要注意的是咋提交賬號密碼時要對信息使用 md5.js 加密。

/**
  *test.html文件
  */
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
    <title>課表登錄</title>
</head>
<body>
<form action="./php/login.php" method="post">
    <div class="form-group">
        <input type="hidden" name="password" value="" id="password">
        <input type="hidden" name="validate" value="" id="validate">
    </div>
    <div class="form-group">
        <label for="id">學號:</label>
        <input type="number" class="form-control" id="id" name="txt_asmcdefsddsd" placeholder="" onblur="chkpwd()" onkeyup="chkpwd()">
    </div>
    <div class="form-group">
        <label for="exampleInputPassword1">密碼:</label>
        <input type="password" class="form-control" id="exampleInputPassword1"  name="txt_pewerwedsdfsdff" placeholder="Password" onblur="chkpwd()" onkeyup="chkpwd()">
    </div>
    <div class="form-group">
        <label for="exampleInputValidate">驗證碼:</label>
        <input type="text" class="form-control" id="exampleInputValidate" name="validatessss" placeholder="" onblur="chkyzm()" onkeyup="chkyzm()">
        <img src="./php/getValidate.php" onclick="changeValidateCode()" alt="" id="validateImg">
    </div>

    <button type="submit" class="btn btn-default">登錄</button>
</form>
<script  src="./js/jquery-3.2.1.min.js"></script>
<script  src="./js/md5.js"></script>
<script>

    function changeValidateCode(){
        var Obj = $('#validateImg');
        var dt = new Date();
        var src = "./php/getValidate.php?t="+dt.getMilliseconds();
        Obj.attr('src', src);
    }

    function chkpwd() {
        var obj = $('#exampleInputPassword1');
        if(obj.val()!='')  {
            var s = md5($('#id').val()+md5(obj.val()).substring(0,30).toUpperCase()+'10467').substring(0,30).toUpperCase();
            $('#password').attr("value",s);
        } else {
            $('#password').attr("value",'');
        }
    }
    function chkyzm() {
        var obj = $('#exampleInputValidate');
        if(obj.val()!='') {
            var s=md5(md5(obj.val().toUpperCase()).substring(0,30).toUpperCase()+'10467').substring(0,30).toUpperCase();
            $('#validate').attr("value",s);
        } else {
            $('#validate').attr("value",'');
        }
    }
</script>
</body>
</html>

我們來獲取驗證碼 ,注意的是我是吧Cookie存儲到了本地

/**
  */php/getValidate.php文件
  */
<?php
//Cookie存儲文件
$cookie_file = dirname(__FILE__)."/../cookie/tmp.cookie";
if(!file_exists($cookie_file)) {
    $myfile = fopen($cookie_file, "w");
    fclose($myfile);
}
$t = isset($_GET['t'])?$_GET['t']:0;
$verify_code_url = "http://jwgl.xxxxxx.edu.cn/jwweb/sys/ValidateCode.aspx?t=".$t;

//不用糾結那條需要不需要,直接header都寫上是不會錯的
$header = [
    'Accept:image/webp,image/apng,image/*,*/*;q=0.8',
    'Accept-Encoding:gzip, deflate',
    'Accept-Language:zh-CN,zh;q=0.8',
    'Cache-Control:no-cache',
    'Connection:keep-alive',
    'Host:jwgl.xxxx.edu.cn',  //修改名稱
    'Pragma:no-cache',
    'Referer:http://jwgl.xxxxx.edu.cn/jwweb/_data/login.aspx',//修改名稱
    'User-Agent:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.86 Safari/537.36',
];

$curl = curl_init();
curl_setopt($curl,CURLOPT_HTTPHEADER,$header);  //設置表頭
curl_setopt($curl, CURLOPT_URL, $verify_code_url); // 設置請求地址
curl_setopt($curl,CURLOPT_COOKIEJAR,$cookie_file); //獲取COOKIE並存儲

$img = curl_exec($curl);
curl_close($curl);

//輸出圖片到html
echo $img;

當進入test.html 時,cookie文件夾下就有存儲的Cookie了
這裏寫圖片描述

4. 模擬登陸

然後我們模擬登錄,主要的地方是要用之前存儲的Cookie和用Post請求

//Cookie路徑
$cookie_file = dirname(__FILE__)."/../cookie/tmp.cookie";
$url = 'http://jwgl.xxxx.edu.cn/jwweb/_data/index_LOGIN.aspx';
$post = [
    '__VIEWSTATE' => 'dDw4ODEwMTkyNTY7Oz6uXw9RQf0bw8SrGIjZutgOtpxLCw==',
    '__VIEWSTATEGENERATOR' =>'4B596BA9',
    'pcInfo' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3080.5 Safari/537.36undefined5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3080.5 Safari/537.36 SN:NULL',
    'typeName' => '(unable to decode value)',
    'dsdsdsdsdxcxdfgfg' => $_POST['password'],
    'fgfggfdgtyuuyyuuckjg' => $_POST['validate'],
    'Sel_Type' => 'STU',
    'txt_asmcdefsddsd' => $_POST['txt_asmcdefsddsd'],
    'txt_pewerwedsdfsdff'=> '',
    'txt_sdertfgsadscxcadsads' => '',
    'sbtState' => '',
];
$post = http_build_query($post);
$headers = array(
    "Accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
    "Accept-Encoding:gzip, deflate",
    "Accept-Language:zh-CN,zh;q=0.8",
    "Cache-Control:max-age=0",
    "Content-Length:603",
    "Content-Type:application/x-www-form-urlencoded",
    "Host:jwgl.xxxx.edu.cn",
    "Origin:http://jwgl.xxxx.edu.cn",
    "Proxy-Connection:keep-alive",
    "Referer:http://jwgl.xxxx.edu.cn/jwweb/_data/index_LOGIN.aspx",
    "Upgrade-Insecure-Requests:1",
    "User-Agent:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3080.5 Safari/537.36",
);
$curl = curl_init();
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);//設置header
curl_setopt($curl, CURLOPT_URL, $url);  //設置url
curl_setopt($curl, CURLOPT_POST, true); // 設置爲POST請求
curl_setopt($curl, CURLOPT_RETURNTRANSFER,1); // 將curl_exec()獲取的信息以文件流的形式返回,而不是直接輸出。
curl_setopt($curl, CURLOPT_POSTFIELDS, $post); //傳送的數據
curl_setopt($curl, CURLOPT_COOKIEFILE, $cookie_file);  //設置cookie

$result=curl_exec($curl);

//可以輸出當前信息看看是否登錄成功
//$file = dirname(__FILE__)."/../html/test.html";
//$fp = fopen($file,"w");
//fwrite($fp,$result);
//fwrite($fp, '結束');
//fclose($fp);

5. 獲取數據

到此,我們已經登錄成功了,然後我們就可以進入系統提取數據了,比如提取課表信息。
這裏寫圖片描述

$curl = curl_init();
$url = 'http://jwgl.xxx.edu.cn/jwweb/wsxk/stu_zxjg_rpt.aspx';
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER,1);
curl_setopt($curl, CURLOPT_COOKIEFILE, $cookie_file);
$result=curl_exec($curl);

$file = dirname(__FILE__)."/../html/test.html";

$fp = fopen($file,"w");
fwrite($fp,$result);
fclose($fp);

6. 提取數據

當我們得到網頁文本時,並不是我們的最終目的,我們要的是其中除了html標籤之外的數據。關於提取數據,我推薦大家使用symfony/dom-crawler,再配合他的symfony/css-selector來將html文本轉換成結點,通過CSS選擇器方式定位結點獲取相應的數據。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章