在php中采集數據最常用的就是使用curl函數來操作,因為curl函數是高性能并且多線程功能,下面我來介紹一個php采集程序,各位同學有需要可進入參考.
php里常用的遠程采集函數,代碼如下:
/**
* 獲取遠程url的內容
* @param string $url
* @return string
*/
function get_url_content($url) {
if(function_exists(curl_init)) {
$ch = curl_init();
$timeout = 5;
curl_setopt ($ch, CURLOPT_URL, $url);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
curl_setopt ($ch, CURLOPT_TIMEOUT, $timeout);
//開源代碼phpfensi.com
$file_contents = curl_exec($ch);
curl_close($ch);
} else {
$file_contents = file_get_contents($url);
}
return $file_contents;
}
調用方法,代碼如下:
$url = 'http://www.bcty365.com';
$a = get_url_content($url);
echo $a;
上面只是一個簡單的實例,如果我們想應用可參考我自己寫的采集程序了.
1,獲取目標網頁數據;2,截取相關內容;3,寫入數據庫/生成HMTL文件;
下面就按照步驟來試試!
獲取目標網頁數據
1, 確定好,要獲取的網頁地址甚至形式,這里我們采用的網址是:/index.html?pageconfig=catalog_byproducttype&intProductTypeID=1&strStartChar=A&intResultsPage=1&tr=59,這個頁面是有分頁的,根據規律,我們找到只需要改變page參數就可以翻頁!即:我們的網頁形式是:/index.html?pageconfig=catalog_byproducttype& amp;intProductTypeID=1&strStartChar=A&intResultsPage= NUMBER &tr=59
紅色部分是當前頁碼對應值!只需要改變該值就可以了!
2,獲取頁面內容:自然要用到PHP函數了!這里,兩個函數都可以!他們分別是:
file_get_contents() 把整個文件讀入一個字符串中。和 file() 一樣,不同的是file_get_contents() 把文件讀入一個字符串。file_get_contents() 函數是用于將文件的內容讀入到一個字符串中的首選方法。如果操作系統支持,還會使用內存映射技術來增強性能。語法: file_get_contents( path , include_path , context , start , max_length ) curl() 了解詳細,請參閱官網文檔:http://cn.php.net/curl fopen()函數打開文件或者 URL。如果打開失敗,本函數返回 FALSE。語法: fopen(filename,mode,include_path,context)當然,我們采用的是第一個!其實,所有的都差不多,有興趣的童子可以常識常識其他的!代碼如下:
<?php
$oldcontent = file_get_contents(“http://www.abcam.cn/index.html?pageconfig=catalog_byproducttype&intProductTypeID=1&strStartChar=A&intResultsPage=2&tr=59”);
echo $oldcontent;
?>
運行PHP程序,上面的代碼可以顯示出整個網頁!由于原網頁采用的是絕地路徑,所以現在顯示的效果和原來的是一模一樣的!
接下來就是要,截取內容了!截取內容的方法也有很多,今天介紹的一種比較簡單,代碼如下:
<?php
$oldcontent = file_get_contents(“http://www.abcam.cn/index.html?pageconfig=catalog_byproducttype&intProductTypeID=1&strStartChar=A&intResultsPage=2&tr=59″);
$oldcontent;
$pfirst = ‘<table border=”0″ cellspacing=”0″ cellpadding=”0″> <tr> <th style=”padding-left: 0px;”><p style=”font-size:12px”><strong>Code</strong></p></th>’;
$plast = ‘Goat polyclonal’;
$b= strpos($oldcontent,$pfirst);
$c= strpos($oldcontent,$plast);
echo substr($oldcontent,$b,$c-1);
?>
輸出的,即為所需要的結果,寫入數據庫和寫入文件都是比較簡單的,這里就寫入文件了,代碼如下:
<?php
$oldcontent = file_get_contents(“index.html?pageconfig=catalog_byproducttype&intProductTypeID=1&strStartChar=A&intResultsPage=2&tr=59″);
$oldcontent;
$pfirst = ‘<table border=”0″ cellspacing=”0″ cellpadding=”0″> <tr> <th style=”padding-left: 0px;”><p style=”font-size:12px”><strong>Code</strong></p></th>’;
$plast = ‘Goat polyclonal’;
$b= strpos($oldcontent,$pfirst);
$c= strpos($oldcontent,$plast);
$a = substr($oldcontent,$b,$c-1);
$file = date(‘YmdHis’).”.html”;
$fp = fopen($file,”w+”);
if(!is_writable($file)){
die(“File “.$file.” can not be written”);
}
else {
file_put_contents($file, $a);
echo “success”;
}
fclose($fp);
?>
新聞熱點
疑難解答