最新下载
热门教程
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
使用PHP抓取微博数据实现demo及原理解析
时间:2026-09-21 17:50:01 编辑:袖梨 来源:一聚教程网
实现目标
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日期时间函数date()详解 09-21
- OKX身份认证为什么失败?证件、人脸与账号原因解析 09-21
- php实现根据中奖概率抽奖的算法 09-21
- PHP使用Guzzle发起的异步请求示例详解 09-21
- 百人共学AI网站的架构是如何搭起来的 09-21
- 手机如何数清一堆硬币:拆解边缘检测、轮廓提取与模板匹配 09-21