以前寫ASP的時候,要實現採集功能,那簡直就是一個浩浩蕩蕩的大工程,現在用PHP簡單多了,輕輕鬆鬆簡簡單單就能把ASP長篇大論才能實現的功能搞定.
這是我用PHP的CURL寫的一個採集Discuz的例子,附帶類比登陸,如果不需要類比登陸就可以直接用File_Get_Contents來采那會更簡單.
<?php
set_time_limit(0);
//cookie儲存目錄
$cookdir = './cookie.tmp';
//類比請求資料
Function request($url,$action,$cookdir,$referer){
$ch = curl_init();
$options = array(CURLOPT_URL => $url,
CURLOPT_HEADER => 0,
CURLOPT_NOBODY => 0,
CURLOPT_PORT => 80,
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => $action,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_FOLLOWLOCATION => 1,
CURLOPT_COOKIEJAR => $cookdir,
CURLOPT_COOKIEFILE => $cookdir,
CURLOPT_REFERER => $referer
);
curl_setopt_array($ch, $options);
$code = curl_exec($ch);
curl_close($ch);
return $code;
}
//擷取貼文清單
Function getList($code){
//<a href="viewthread.php?tid=16&extra=page%3D1">加打塔洗花腳本</a>
preg_match_all('/<a href=\"viewthread.php\?tid=(\d+)/',$code,$threads);
return $threads[1];
}
//判斷該文章是否存在
Function isExits($code){
preg_match('/<p>指定的主題不存在或已被刪除或正在被審核,請返回。<\/p>/',$code,$error);
return isset($error[0])?false:true;
}
//擷取文章標題
Function getTitle($code){
preg_match('/<h1>[^<\/h1>]*/',$code,$title_tmp);
$title = $title_tmp[0];
return $title;
}
//登入論壇/
$url = 'http://www.175club.com/logging.php?action=login';
$action='loginfield=username&username=see7di&password=fjin999&questionid=0&cookietime=315360000&referer=http://bbs.war3.cn/&loginsubmit=提交';
request($url,$action,$cookdir,'');
unset($action,$url);
//擷取貼文清單(位於第一頁的文章)
$url = 'http://www.175club.com/forumdisplay.php?fid=5';
$code = request($url,'',$cookdir,'');
$tList = getList($code);
//迴圈抓取每個文章內的標題
foreach($tList as $list){
$url = "http://www.175club.com/viewthread.php?tid={$list}";
$code = request($url,'',$cookdir,'');
if(isExits($code)){
$title = getTitle($code);
echo "tid:{$list}:",strip_tags($title),"<br>";
}else{
echo "tid:{$list}:該文章不存在!<br>";
}
}
?>