使用PHP抓取微博數(shù)據(jù)實現(xiàn)demo及原理解析
實現(xiàn)目標
1. 用戶發(fā)布的微博內(nèi)容;
2. 用戶發(fā)布的時間;
3. 用戶的名稱; (這里我并沒有獲取)
使用的工具
voku/simple_html_dom x-path
讀取工具 (如果不知道怎么獲取元素的xpath, 請百度這里不做贅述~)
安裝:
composer require voku/simple_html_dom
實現(xiàn)的原理
當你去直接用file_get_contents去抓取微博的網(wǎng)頁內(nèi)容時, 你會被它的訪客系統(tǒng)直接攔截, 所以直接用這個方法是不行的;
所以我采用了curl來獲取. 當然,直接獲取也是不行的, 所以我們要設置一下請求頭, 微博對爬蟲類的請求頭是不會拒絕的,
所以你可以直接抓取到網(wǎng)頁;
請求頭設置如下:
'User-Agent: spider'
代碼如下:
// 通過這段代碼你可以直接獲取到微博的(HTML)網(wǎng)頁
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(); // 初始化curl
curl_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);
// 到這里我們就拿到了微博的網(wǎng)頁
return $wbContent;
}拿到微博的網(wǎng)頁內(nèi)容之后, 我們就要對立面的數(shù)據(jù)進行提取, 因為并不是所有的數(shù)據(jù)我們都需要;
這里我們提取 微博內(nèi)容 微博發(fā)布的時間; 現(xiàn)在需要使用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抓取微博數(shù)據(jù)實現(xiàn)demo及原理解析的詳細內(nèi)容,更多關于PHP抓取微博數(shù)據(jù)的資料請關注腳本之家其它相關文章!
相關文章
PHP迭代器實現(xiàn)斐波納契數(shù)列的函數(shù)
斐波納契數(shù)列通常做法是用遞歸實現(xiàn),當然還有其它的方法。這里現(xiàn)學現(xiàn)賣,用PHP的迭代器來實現(xiàn)一個斐波納契數(shù)列,幾乎沒有什么難度,只是把類里的next()方法重寫了一次。注釋已經(jīng)寫到代碼中,也是相當好理解的2013-11-11

