PHP網絡爬蟲--新聞抓取

README:一個能向指定郵箱推送所關心新聞內容的插件,測試環境:LAMP+Chrome/Firefox,分下面幾個步驟實現:

1.獲取目標網站源代碼:

實現方法:PHP的curl類

ubuntu下的安裝方法:

#sudo apt-get install curl libcurl3 libcurl3-dev php5-curl

然戶重啓Apache服務:

#sudo /etc/init.d/apache2 restart

function GetHtmlCode($url){
	$ch = curl_init();//初始化一個cur對象
	curl_setopt ($ch, CURLOPT_URL, $url);//設置需要抓取的網頁
	curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);//設置crul參數,要求結果保存到字符串中還是輸出到屏幕上
	curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT,1000);//設置鏈接延遲
	$HtmlCode = curl_exec($ch);//運行curl,請求網頁
	return $HtmlCode;
}

2.用正則表達式截取出源代碼中的所有鏈接:

//參數說明:$string=GetHtmlCode($url)

function GetAllLink($string) { 
	  $string = str_replace("\r","",$string); 
	  $string = str_replace("\n","",$string); 
	  $regex[url] = "((http|https|ftp|telnet|news):\/\/)?([a-z0-9_\-\/\.]+\.[][a-z0-9:;&#@=_~%\?\/\.\,\+\-]+)";  
          $regex[email] = "([a-z0-9_\-]+)@([a-z0-9_\-]+\.[a-z0-9\-\._\-]+)";   

	    
	  //去掉網頁中的[]
	  $string = eregi_replace("\[|\]","",$string);

          //去掉JAVASCRIPT代碼 
          $string = eregi_replace("<!--.*//-->","", $string); 
           
          //去掉非<a>的HTML標籤   
	  $string = eregi_replace("</?[^aA][^<>]*>","",$string);
          //分割$string中的所有鏈接       
	  $output = split('</a>', $string);
	  for($i=0; $i<count($output); $i++){
		 $output_1 = split("<a", $output[$i]);
	  }
 	  return $output_1; 
} 

3.這步則是獲取用戶關心的鏈接:

//參數說明:$test=GetAllLink($string);$keywords是用戶提交的關鍵字(支持多關鍵字,他們之間使用";"隔開);$url是目標根網站目錄(爲某些鏈接加上根鏈接)

function GetUserCareNews ($test,$keywords,$url) {
	$messTxt = "";
	$k=0;
	$key = explode(";",$keywords);

	//自動爲網站加載上http,避免網易郵箱鏈接錯誤,有一定的侷限性
	if(!ereg("http",$url)){
		$url = "http://".$url;
	}

	for($i=0; $i<count($test); $i++){
		$test[$i] = eval('return'.iconv('gbk','utf-8',var_export($test[$i],true)).';');//修改編碼
		if(ereg("href", $test[$i])  && !ereg("href='#'",$test[$i])){//去掉無效鏈接
			for($j=0; $j<count($key); $j++){                    //支持多關鍵字
				if(strpos($test[$i],$key[$j])!==false){
					$mess[$k++]=ereg_replace($key[$j],"<font color=red>".$key[$j]."</font>", $test[$i]);//高亮關鍵字
			}
			}
		}
	}
	$mess = array_unique($mess);		//數組去重
	
	//處理好發送鏈接,爲鏈接加上網站根目錄
	for($l=0; $l<count($mess); $l++){
		if(!ereg("http",$mess[$l]) && (strlen($mess[$l]) != 0)){//去掉空數組,這步很重要,如果不去掉直接影響後面鏈接的質量
				$mess[$l] = eregi_replace("href=[\"']","",$mess[$l]);
				$mess[$l] = $url.$mess[$l];
				$mess[$l] = eregi_replace(" /","/",$mess[$l]);
				if(ereg("'",$mess[$l])){
					$mess[$l]="<a href='".$mess[$l]."</a>";
				}
				if(ereg("\"",$mess[$l])){
					$mess[$l] = "<a href=\"".$mess[$l]."</a>";
				}
		}
		else{
			$mess[$l] = "<a ".$mess[$l]."</a>";
		}
		$messTxt .= $mess[$l];
		$messTxt .= "<BR>";
	}
	return $messTxt;
}

4.向用戶郵箱推送信息:

實現方法:PHP的PHPMailer類

下載地址:http://sourceforge.net/projects/phpmailer/files/

下載完成後解壓得到:class.phpmailer.php和class.smtp.php兩個類,在自己的PHP文件中引入即可:

include "/路徑/class.phpmailer.php";

include "/路徑/class.smtp.php";

//參數說明:$content=GetUserCareNews($test,$keywords,$url)

function SendEmail($to, $content) {
	//Author:luofei
	//$to 表示收件人地址,$content表示郵件正文內容
	
	error_reporting(E_STRICT);						//錯誤報告
	date_default_timezone_set("Asia/Shanghai");		//設定時區

	require_once("class.phpmailer.php");
	require_once("class.smtp.php");

	$mail = new PHPMailer();						//新建一個對象
	$mail->CharSet = "UTF-8";						//設置編碼,中文不會出現亂碼的情況
	$mail->IsSMTP();								//設定使用SMTP服務
	$mail->SMTPDebug = 1;							//啓用SMTP調試功能i
													//1 = errors and messages
													//2	= messages only

	$mail->SMTPSecure = "tls";						//安全協議
	$mail->Host = "smtp.googlemail.com";			//SMTP服務器        
	$mail->SMTPAuth = true;							//啓用SMTP驗證功能	
	$mail->Username = "[email protected]";                 //SMTP服務器用戶名      
	$mail->Password = "******";					//SMTP服務器用戶密碼
        
	$mail->From = "[email protected]";                    //發件人                            
	$mail->FromName = "Spider Service";						//發件人姓名(郵件上顯示)
        
	$mail->AddAddress($to);							//收件人地址
	$mail->WordWrap   = 50;							//設置郵件正文每行的字符數
	$mail->IsHTML(true);							//設置郵件正文內容是否爲html類型
        
	$mail->Subject = "來自spider.html的郵件";		//郵件主題
	$mail->Body = "<p>您好!<BR> <p>這是您感興趣的內容</p> <BR>".$content." ";
													//郵件正文
	if(!$mail->Send())								//郵件發送報告
	{
	   echo "發送郵件錯誤!";
	} 
	else
	{
	   echo "郵件發送成功!";
	}
}

測試結果:

除新浪外的網站基本都行,由於這個默認只爬去當前網頁中的鏈接,沒有更深入的爬取,故耗時一般不長。然後郵件測試結果:gmail/126/163/qq/sina...都沒問題,均能正常打開鏈接。

contact me:[email protected]

Github:https://github.com/luofei2011/SendNewsTimely

PS:這是我在CSDN上的第一篇博文,雖然博主很早就開始寫博文(新浪博客無故被封),思索良久......一直沒能找見好的開篇,希望從這篇博文發表開始能重拾我寫博的興趣,無論質量如何,但求無愧於心!come on!!!




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章