PHP 實現新浪微博自動評論及爬取微博id
阿新 • • 發佈:2018-12-20
public function jiaoben(){ $code = $this->request->param('code'); $access_token = session('access'); echo $access_token; if($code && !$access_token){ $ret = $this->getcode($code); $arr = json_decode($ret,true); if($arr['expires_in'] == 3600){ session('access',$arr['access_token']); } } $url_token = "https://api.weibo.com/oauth2/access_token";//獲取token $url_code = "https://api.weibo.com/oauth2/authorize";//獲取code $code_data = "client_id=&response_type=code&redirect_uri=https://ceshi.yunyihw.com";//code資料 $postdata = "client_id=&client_secret=&grant_type=authorization_code&code=&redirect_uri=https://ceshi.yunyihw.com";//token資料 /* $url = 'https://api.weibo.com/2/comments/create.json';//評論url */ /* $pp = "access_token=2.00DxpcuF0ah4yQe504a76ee8YSHSdC&comment=".urlencode('你好啊,很高興見到你')."&id=4303785897751981";//評論資料 */ $data_url = 'https://api.weibo.com/2/search/topics.json'; $pp = "access_token=2.00DxpcuF0ah4yQe504a76ee8YSHSdC&q=".urlencode('你好啊,很高興見到你')."&count=30";//資料 /* $ret = Post($pp,$data_url); */ return $this->fetch('jiaoben'); } public function getcode($code){ $url_token = "https://api.weibo.com/oauth2/access_token";//獲取token $postdata = "client_id=&client_secret=&grant_type=authorization_code&code=".$code."&redirect_uri=https://ceshi.yunyihw.com/Hospital/jiaoben.html"; $ret = Post($postdata,$url_token); return $ret; } public function pinglun(){ $mids = $this->request->param('mids'); $contents = $this->request->param('content'); $content = urlencode($contents); $access_token = session('access'); $midss = array_filter(explode(',',$mids)); if($midss){ foreach($midss as $k=>$v){ $mid = $v; $pp = "access_token=".$access_token."&comment=".$content."&id=".$mid;//評論資料 $url = 'https://api.weibo.com/2/comments/create.json';//評論url $ret = Post($pp,$url); $c = $k+1; echo "完成".$c."個"; echo "</br>"; } } /* echo "<pre>"; */ /* print_r($mid);die; */ // $pp = "access_token=".$access_token."&comment=".$content."&id=".$mid;//評論資料 // $url = 'https://api.weibo.com/2/comments/create.json';//評論url // $ret = Post($pp,$data_url); }
具體步驟:授權拿到code-》用code換取access_token-》實現功能
爬蟲程式碼
<?php require 'vendor/autoload.php'; use QL\QueryList; $url = 'https://s.weibo.com/weibo?q=%E7%9C%8B%E7%9C%8B%E9%80%9F%E5%BA%A6%E6%89%A9%E4%BB%98%E5%86%9B%E5%86%9B%E5%86%9B%E5%86%9B&typeall=1&suball=1×cope=custom:2018-11-07:2018-11-09&Refer=SWeibo_box'; $data = QueryList::get($url)->find('div')->attrs('mid'); $arr = array_filter($data->all()); $cc = implode(',',$arr); echo "<pre>"; print_r($cc);