如何處理simple_html_dom load_file 逾時的問題?

來源:互聯網
上載者:User
我用simple_html_dom 爬取網頁,用的物件導向方式,但是會出現逾時的情況。

set_time_limit(10000);ini_set('default_socket_timeout', 5);$context = stream_context_create(    array(        'http'=>array(            'method' => 'GET',             'timeout' => 5        ),    ));$shd->load_file($player_url, false, $contex);

我用上面的代碼做限時處理,可是不起作用。當時間超過10000秒時會退出指令碼,但是我希望一條請求逾時後會終止這條請求,然後重新發起請求或進行下一條請求。大神有好的辦法嗎?

回複內容:

我用simple_html_dom 爬取網頁,用的物件導向方式,但是會出現逾時的情況。

set_time_limit(10000);ini_set('default_socket_timeout', 5);$context = stream_context_create(    array(        'http'=>array(            'method' => 'GET',             'timeout' => 5        ),    ));$shd->load_file($player_url, false, $contex);

我用上面的代碼做限時處理,可是不起作用。當時間超過10000秒時會退出指令碼,但是我希望一條請求逾時後會終止這條請求,然後重新發起請求或進行下一條請求。大神有好的辦法嗎?

不要直接使用它提供的介面擷取網路上的內容,雖然它具備這個能力,但這也只是給你調試的時候使用的。在真實情況下很容易碰到如你問題中所述的逾時情況,所以你最好先用curl介面來擷取內容,然後再用simple_html_dom 來處理這個內容,前者可以很方便地處理各種網路錯誤

function get_html_by_url($url, $timeout = 5) {    $ch = curl_init();        curl_setopt($ch, CURLOPT_URL, $url);    curl_setopt($ch, CURLOPT_HEADER, false);    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);        // 自動識別301跳轉    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);        // 設定各種逾時限制    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);    curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);        $html = curl_exec($ch);        // 處理各種錯誤    if (false === $html) {        return false;    }        // 處理http錯誤    if (200 != curl_getinfo($ch, CURLINFO_HTTP_CODE)) {        return false;    }        return $html;}// 直接使用$html = get_html_by_url('http://www.sina.com.cn', 5);// 用simple_html_dom載入if (false !== $html) {    $shd->load($html);}

配合set_time_limit(0);,必要時,適當增大default_socket_timeout

  • 相關文章

    聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.