文章詳情頁
使用PHP抓取微博數據實現demo及原理解析
瀏覽:4日期:2022-06-14 10:15:05
目錄實現目標使用的工具實現的原理實現目標
1. 用戶發布的微博內容;
2. 用戶發布的時間;
3. 用戶的名稱; (這里我并沒有獲取)
使用的工具voku/simple_html_dom x-path
讀取工具 (如果不知道怎么獲取元素的xpath, 請百度這里不做贅述~)
安裝:
composer require voku/simple_html_dom
實現的原理當你去直接用file_get_contents去抓取微博的網頁內容時, 你會被它的訪客系統直接攔截, 所以直接用這個方法是不行的;
所以我采用了curl來獲取. 當然,直接獲取也是不行的, 所以我們要設置一下請求頭, 微博對爬蟲類的請求頭是不會拒絕的,
所以你可以直接抓取到網頁;
請求頭設置如下:
'User-Agent: spider'代碼如下:
// 通過這段代碼你可以直接獲取到微博的(HTML)網頁 public function curlGetWbData() {// 設置腳本超時時間set_time_limit(60);// 拉取微博地址$getWbUrl = 'https://weibo.com/p/1005056447467552/home?profile_ftype=1&is_all=1#_0';// 設置curl 請求頭$header = [ 'User-Agent: spider'];$ch = curl_init(); // 初始化curlcurl_setopt($ch, CURLOPT_URL, $getWbUrl);curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 禁止 cURL 驗證對等證書curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);curl_setopt($ch, CURLOPT_HTTPHEADER, $header); // 設置請求頭$wbContent = curl_exec($ch);curl_close($ch);// 到這里我們就拿到了微博的網頁return $wbContent; }拿到微博的網頁內容之后, 我們就要對立面的數據進行提取, 因為并不是所有的數據我們都需要;
這里我們提取 微博內容 微博發布的時間; 現在需要使用x-path來進行提取;
x-path示例:
div[class='WB_cardwrap WB_feed_type S_bg2 WB_feed_like ']代碼如下:
// 這個方法是public static function actionAddWbData(string $wbContent, string $userID){ $htmlDeal = new HtmlDomParser(); // 處理DOM的對象 $htmlDeal->load($wbContent);// 裝載文本 // 微博VIP和普通用戶的class名不一致 $wbHtml['normal'] = $htmlDeal->find('div[class='WB_cardwrap WB_feed_type S_bg2 WB_feed_like ']'); $wbHtml['vip'] = $htmlDeal->find('div[class='WB_cardwrap WB_feed_type S_bg2 WB_feed_vipcover WB_feed_like ']'); $wbNum = []; foreach ($wbHtml as $item => $key) {if (count($key) <= 0) { continue;}$wbNum[$userID][$item] = self::dealWbContent($key, $userID); } Yii::info('抓取微博日志記錄' . '----' . json_encode($wbNum)); return $wbNum;}以上就是使用PHP抓取微博數據實現demo及原理解析的詳細內容,更多關于PHP抓取微博數據的資料請關注好吧啦網其它相關文章!
標簽:
PHP
排行榜