這是一個系列 沒辦法在一兩天寫完 所以一篇一篇的發(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)站首頁采集來做例子講解
最簡單的寫法:
復(fù)制代碼 代碼如下:
$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;
}
復(fù)制代碼 代碼如下:
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;
}
復(fù)制代碼 代碼如下:
$url = 'http://www.baidu.com';
echo get_html($url);
復(fù)制代碼 代碼如下:
$url = 'http://www.163.com';
echo get_html($url);
復(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ù)了: 復(fù)制代碼 代碼如下:
$url = 'http://www.163.com';
$options[CURLOPT_FOLLOWLOCATION] = true;
echo get_html($url,$options);
會發(fā)現(xiàn) 怎么是這樣的一個頁面 和我們電腦訪問的不同???
看來參數(shù)還是不夠 不夠服務(wù)器判斷我們的客戶端是什么設(shè)備上的 就返回了個普通版
看來還要傳送USERAGENT 復(fù)制代碼 代碼如下:
$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
當(dāng)然也有另外的辦法可以實現(xiàn),當(dāng)你明確的知道網(wǎng)易的網(wǎng)頁的時候就可以簡單采集了:
復(fù)制代碼 代碼如下:
$url = 'http://www.163.com/index.html';
echo get_html($url);
新聞熱點
疑難解答