实现目标
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;
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。