php抓取运动步数,使用PHP抓取微博数据
實現目標
1. 用戶發布的微博內容;
2. 用戶發布的時間;
3. 用戶的名稱; (這里我并沒有獲取)
使用的工具
1. 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(); // 初始化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);
// 到這里我們就拿到了微博的網頁
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抓取运动步数,使用PHP抓取微博数据的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: anaconda怎么使用python包_
- 下一篇: php 网页截屏,怎么用PHP实现网页截