2019-01-07 10:40:27 1393瀏覽
今天扣丁學堂PHP培訓老師給大家分享一篇關于PHP一個簡單的無需刷新爬蟲的小示例,下面我們一起來看一下吧。
<?php //設置最大執(zhí)行時間 set_time_limit(0); function getHtml($url){ // 1. 初始化 $ch = curl_init(); // 2. 設置選項,包括URL curl_setopt($ch,CURLOPT_URL,$url); curl_setopt($ch,CURLOPT_RETURNTRANSFER,1); curl_setopt($ch,CURLOPT_HEADER,0); // 3. 執(zhí)行并獲取HTML文檔內(nèi)容 $output = curl_exec($ch); if($output === FALSE ){ $output = ''; } // 4. 釋放curl句柄 curl_close($ch); return $output; } function getPageData($url){ // 獲取整個網(wǎng)頁內(nèi)容 $html = getHtml($url); // 初步獲取主塊內(nèi)容 preg_match("/教程列表.*教程列表/s",$html,$body_html); // 返回數(shù)據(jù) $data = array(); //判斷是否存在要獲取的內(nèi)容 if(count($body_html)){ // 獲取頁面指定信息 preg_match_all('/<a class="avatar".*user_id="(\S*)" href="(\S*)" rel="external nofollow" /',$body_html[0],$info_1); preg_match_all('/<a href="(.*)" rel="external nofollow" .*title="(.*)"/',$body_html[0],$info_2); $info = array_merge($info_1,$info_2); //組合的信息 for($index=0; $index<count($info[0]); $index++){ //以文章信息作為key存數(shù)組,以及覆蓋舊數(shù)據(jù) $data[$info[4][$index]] = array( 'user_id' => $info[1][$index], 'user_home' => $info[2][$index], 'a_url' => $info[4][$index], 'a_title' => $info[5][$index], ); } } return $data; } header("Content-type: text/html; charset=utf-8"); echo '<pre>'; // 初始化數(shù)據(jù) $page_no = 1; $data_all = array(); // 分頁獲取數(shù)據(jù) do{ $url = 'http://m.dionly.net.cn/article?page=2' . $page_no; $data = getPageData($url); $data_all += $data; $page_no ++; }while ($page_no <= 10); //當前只獲取10頁,如果要全部獲取則把條件換成$data或!empty($data) var_dump($data_all); ?>
【關注微信公眾號獲取更多學習資料】