基于curl數(shù)據(jù)采集之單頁面采集函數(shù)get_html的使用
這是一個系列 沒辦法在一兩天寫完 所以一篇一篇的發(fā)布
大致大綱:
1.curl數(shù)據(jù)采集系列之單頁面采集函數(shù)get_html
2.curl數(shù)據(jù)采集系列之多頁面并行采集函數(shù)get_htmls
3.curl數(shù)據(jù)采集系列之正則處理函數(shù)get _matches
4.curl數(shù)據(jù)采集系列之代碼分離
5.curl數(shù)據(jù)采集系列之并行邏輯控制函數(shù)web_spider
單頁面采集在數(shù)據(jù)采集過程中是最常用的一個功能 有時在服務(wù)器訪問限制的情況下 只能使用這種采集方式 慢 但是可以簡單的控制 所以寫好一個常用的curl函數(shù)調(diào)用是很重要的
百度和網(wǎng)易比較熟悉 所以拿這兩個網(wǎng)站首頁采集來做例子講解
最簡單的寫法:
$url = 'http://www.baidu.com';
$ch = curl_init($url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch,CURLOPT_TIMEOUT,5);
$html = curl_exec($ch);
if($html !== false){
echo $html;
}
由于使用頻繁 可以利用curl_setopt_array寫成函數(shù)的形式:
function get_html($url,$options = array()){
$options[CURLOPT_RETURNTRANSFER] = true;
$options[CURLOPT_TIMEOUT] = 5;
$ch = curl_init($url);
curl_setopt_array($ch,$options);
$html = curl_exec($ch);
curl_close($ch);
if($html === false){
return false;
}
return $html;
}
$url = 'http://www.baidu.com';
echo get_html($url);
有時候需要傳遞一些特定的參數(shù)才能得到正確的頁面 如現(xiàn)在要得到網(wǎng)易的頁面:
$url = 'http://www.163.com';
echo get_html($url);
會看到一片空白 什么也沒有 那么再利用curl_getinfo寫一個函數(shù) 看看發(fā)生了什么:
function get_info($url,$options = array()){
$options[CURLOPT_RETURNTRANSFER] = true;
$options[CURLOPT_TIMEOUT] = 5;
$ch = curl_init($url);
curl_setopt_array($ch,$options);
$html = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
return $info;
}
$url = 'http://www.163.com';
var_dump(get_info($url));

可以看到http_code 302 重定向了 這時候就需要傳遞一些參數(shù)了:
$url = 'http://www.163.com';
$options[CURLOPT_FOLLOWLOCATION] = true;
echo get_html($url,$options);

會發(fā)現(xiàn) 怎么是這樣的一個頁面 和我們電腦訪問的不同???
看來參數(shù)還是不夠 不夠服務(wù)器判斷我們的客戶端是什么設(shè)備上的 就返回了個普通版
看來還要傳送USERAGENT
$url = 'http://www.163.com';
$options[CURLOPT_FOLLOWLOCATION] = true;
$options[CURLOPT_USERAGENT] = 'Mozilla/5.0 (Windows NT 6.1; rv:19.0) Gecko/20100101 Firefox/19.0';
echo get_html($url,$options);

OK現(xiàn)在頁面已經(jīng)出來了 這樣基本這個get_html函數(shù)基本能實現(xiàn)這樣擴展的功能
當然也有另外的辦法可以實現(xiàn),當你明確的知道網(wǎng)易的網(wǎng)頁的時候就可以簡單采集了:
$url = 'http://www.163.com/index.html';
echo get_html($url);
這樣也可以正常的采集
相關(guān)文章
利用PHP?POST臨時文件機制實現(xiàn)任意文件上傳的方法詳解
這篇文章主要介紹了利用?PHP?POST?臨時文件機制實現(xiàn)任意文件上傳,同時該過程也會打斷 php 對臨時文件的處理,雖然最終仍會被刪除,但相較之前可以明顯看出臨時文件在磁盤的中存在的時間變長了,需要的朋友可以參考下2022-04-04

