說到爬蟲,大家的第一印象就會想到Python, 但是Python并不是所有人都會的, 那么是否可以使用其他的語言來編寫爬蟲呢? 當然是可以的,下面介紹一下如何使用PHP編寫爬蟲。
獲取頁面html內容
1、使用函數 file_get_contents 把整個文件讀入一個字符串中。
file_get_contents(path,include_path,context,start,max_length); file_get_contents('https://fengkui.net/');
這樣就可以將整個頁面的html內容,讀入一個字符串中,然后進行解析了
2、使用CURL進行請求,獲取html
/** * [curlHtml 獲取頁面信息] * @param [type] $url [網址] * @return [type] [description] */ function curlHtml($url) { $curl = curl_init(); curl_setopt_array($curl, array( CURLOPT_URL => "{$url}", CURLOPT_RETURNTRANSFER => true, CURLOPT_ENCODING => "", CURLOPT_MAXREDIRS => 10, CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "GET", CURLOPT_HTTPHEADER => array( "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "Accept-Encoding: gzip, deflate, br", "Accept-Language: zh-CN,zh;q=0.9", "Cache-Control: no-cache", "Connection: keep-alive", "Pragma: no-cache", "Upgrade-Insecure-Requests: 1", "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36", "cache-control: no-cache" ), )); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false); $response = curl_exec($curl); $err = curl_error($curl); curl_close($curl); if ($err) return false; else return $response; }
使用Curl我們可以來進行其他操作,如模擬瀏覽器模擬登陸等一些高級操作。
解析頁面HTML,獲取所需數據
1、正則獲取內容
/** * [get_tag_data 使用正則獲取html內容] * @param [type] $html [爬取的頁面內容] * @param [type] $tag [要查找的標簽] * @param [type] $attr [要查找的屬性名] * @param [type] $value [屬性名對應的值] * @return [type] [description] */ function get_tag_data($html,$tag,$attr,$value){ $regex = "/<$tag.*?$attr=".*?$value.*?".*?>(.*?)</$tag>/is"; preg_match_all($regex,$html,$matches,PREG_PATTERN_ORDER); $data = isset($matches[1][0]) ? $matches[1][0] : ''; return $data; } $str = '<div class="feng">馮奎博客</div>'; $value = get_tag_data($str, 'div', 'class', 'feng');
2、使用Xpath解析數據
XPath即為XML路徑語言(XML Path Language),它是一種用來確定XML文檔中某部分位置的語言。 具體使用方法及相關介紹查看百度百科(XPath) 使用方法:
/** * [get_html_data 使用xpath對獲取到的html內容進行處理] * @param [type] $html [爬取的頁面內容] * @param [type] $path [Xpath語句] * @param integer $tag [類型 0內容 1標簽內容 自定義標簽] * @param boolean $type [單個 還是多個(默認單個時輸出單個)] * @return [type] [description] */ function get_html_data($html,$path,$tag=1,$type=true) { $dom = new DOMDocument(); @$dom->loadHTML("<?xml encoding='UTF-8'>" . $html); // 從一個字符串加載HTML并設置UTF8編碼 $dom->normalize(); // 使該HTML規范化 $xpath = new DOMXPath($dom); //用DOMXpath加載DOM,用于查詢 $contents = $xpath->query($path); // 獲取所有內容 $data = []; foreach ($contents as $value) { if ($tag==1) { $data[] = $value->nodeValue; // 獲取不帶標簽內容 } elseif ($tag==2) { $data[] = $dom->saveHtml($value); // 獲取帶標簽內容 } else { $data[] = $value->attributes->getNamedItem($tag)->nodeValue; // 獲取attr內容 } } if (count($data)==1) { $data = $data[0]; } return $data; }
推薦學習:《PHP視頻教程》