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;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值