当前位置: 代码网 > it编程>编程语言>Php > 使用PHP抓取微博数据实现demo及原理解析

使用PHP抓取微博数据实现demo及原理解析

2024年05月19日 Php 我要评论
实现目标1. 用户发布的微博内容;2. 用户发布的时间;3. 用户的名称; (这里我并没有获取)使用的工具voku/simple_html_dom x-path读取工具 (如果不知道怎么获取元素的xp

实现目标

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();                                              // 初始化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抓取微博数据实现demo及原理解析的详细内容,更多关于php抓取微博数据的资料请关注代码网其它相关文章!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com