採集練習(十一) php 得到電視節目預告---數據來自電視貓

  昨天寫了個採集搜視網的電視節目預告,恰好今天有心情,想採下其餘網站提供的節目預告,發現  電視貓wap版 的提供的節目預告也蠻好採(須要正則)....感謝移動互聯網!php

電視貓的 wap版地址是 http://wap.tvmao.com/  點擊相應的電視臺 進去就能看到 相應的 節目預告html

如:http://wap.tvmao.com/cctv.jsp  裏的就是 央視的 相應頻道列表  點擊 相應的 頻道 就能夠看到  該頻道的 的節目預告;數組

http://wap.tvmao.com/program.jsp?p=CCTV&c=CCTV1&w=6  就是 CCTV-1 週六 的節目預告 。curl

分析 頁面html 得知   /program.jsp?p=CCTV&c=CCTV1 來自  http://wap.tvmao.com/cctv.jsp 頁面的頻道列表裏  而 w=6 表示 週六jsp

下面是採集央視的測試代碼:post

 

<?php
/**
 * Created by JetBrains PhpStorm.
 * User: keygle
 * Date: 13-8-3
 * Time: 下午2:04
 * From  www.cnblogs.com/keygle
 */

/**
 * [curl 帶重試次數]
 * @param  [type]  $url     [訪問的url]
 * @param  [type]  $post    [$POST參數]
 * @param  integer $retries [curl重試次數]
 * @return [type]           [description]
 */
function curlGetHtml($url, $post = null, $retries = 3){
    $ch = curl_init();
    if(is_resource($ch) === true){
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_FAILONERROR, true);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_REFERER, "http://wap.tvmao.com/");
        curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.95 Safari/537.36");
        if(isset($post) === true){
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, (is_array($post) === true) ? http_build_query($post, "", "&"): $post);
        }
        $result = false;
        while(($result === false) && (--$retries > 0)){
            $result = curl_exec($ch);
        }
        curl_close($ch);
    }
    return $result;
}

/**
 * [getTvUrl 得到電視臺連接數組]
 * @param  [type] $tvListHtml [頁面html ]
 * @return [type]             [description]
 */
function getTvUrl($tvListHtml){
    $tvListArray = array();
    //正則匹配 url 和 電視臺名
    preg_match_all('#<a href="/([^"]+)">(.*?)</a><br/>#i', $tvListHtml, $matches);
    foreach ($matches[1] as $key => $value) {
        $tvListArray[$key]['url'] ="http://wap.tvmao.com/".html_entity_decode($value); //html 實體轉換
        $tvListArray[$key]['name'] = $matches[2][$key];
    }
    return $tvListArray;
}

/**
 * [getPlayItems 得到電視節目預告]
 * @param  [type] $tvUrl [description]
 * @return [type]        [description]
 */
function getPlayItems($tvUrl){
    $playItems = array();
    $itemHtml = curlGetHtml($tvUrl);
    preg_match_all("#r/>([^<]+)?<b#i", $itemHtml, $matches);
    array_shift($matches[1]); //去掉數組的第一個
    $playItems = $matches[1];
    return $playItems;
}

//得到央視 的全部頻道
$url = "http://wap.tvmao.com/cctv.jsp";
$tvListHtml  = curlGetHtml($url);
$tvListArray = getTvUrl($tvListHtml);
print_r($tvListArray);
// 得到cctv1的 週六 節目預告
$tvUrl = "http://wap.tvmao.com/program.jsp?p=CCTV&c=CCTV1&w=6";
$playItems = getPlayItems($tvUrl);
print_r($playItems);
相關文章
相關標籤/搜索