百度API:频道新闻API_易源

第二个看这个是因为百度APIStore里面免费+综合排序这个就排第二,也是因为公司之前需要新闻采集,自己做的不好。用一下这个看看能有多少有效新闻:

[2]新闻

今天看一共有44个频道,每个频道第一页都可以取20条新闻。很强大。代码很简单:

<html>
 <head><meta charset="utf-8"></head>
 <body>
 <?php
     $ch = curl_init();
     $url = 'http://apis.baidu.com/showapi_open_bus/channel_news/channel_news';
     $header = array(
         'apikey:百度API密钥',
     );
     curl_setopt($ch, CURLOPT_HTTPHEADER  , $header);
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
     curl_setopt($ch , CURLOPT_URL , $url);
     $res = curl_exec($ch);
     $data=json_decode($res,true);
       echo '<pre>';
     $channel=array();//频道
     if(isset($data['showapi_res_code']) && $data['showapi_res_code']===0 && is_array($data['showapi_res_body']['channelList'])){
         $channel=$data['showapi_res_body']['channelList'];         
     }else{
         echo 'error!';
         exit;
     }
     //print_r($data);
     foreach($channel as $v){
         $id=$v['channelId'];
         $name=$v['name'];
 
         $ch = curl_init();
         $url = "http://apis.baidu.com/showapi_open_bus/channel_news/search_news?channelId={$id}&page=1&needContent=1&needHtml=1";
         curl_setopt($ch, CURLOPT_HTTPHEADER  , $header);
         curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
         curl_setopt($ch , CURLOPT_URL , $url);
         $res = curl_exec($ch);
         $data=json_decode($res,true);
         if(isset($data['showapi_res_body']['pagebean']['contentlist']) && is_array($data['showapi_res_body']['pagebean']['contentlist'])){
             //$num=count($data['showapi_res_body']['pagebean']['contentlist']);
             echo ''.$name.':';
              foreach($data['showapi_res_body']['pagebean']['contentlist'] as $dk=>$dv){
                  echo "<a href='{$dv['link']}' style='color:#646'>".$dv['title'].'</a>';
                  foreach($dv['imageurls'] as $iv){
                      echo '<img src="'.$iv['url'].'" style="width:20px;height:20px">';
                  }    
                  echo '&nbsp;&nbsp;&nbsp;&nbsp;';
                  if($dk>3) break; //一类获取三条退出,只做初步查看用
                  //print_r($dv);
              }
          }
          echo '<br/>';
          //break;     
     }
     echo '</pre>';
 ?>
 </body>
 </html>

自己之前给公司做的新闻采集就比较弱,上一篇提到过,就是用file_get_contents()获取内容然后preg_match正则去取,正则用的也属于新手阶段。

说一下当时的新闻采集的思路,就是找新闻列表页,比如:人民网-北京-区县,然后分析出来所有链接,去链接里面去采集新闻标题,内容,图片。数据库存储:`tag`表存储标签,字段名称,链接地址,列表开始结束标签,新闻标题开始结束标签,内容开始结束标签。以后采集时候直接选取名称然后去查询。目标网站改版后得更新。

遇到的难点有:1.编码,GB2312转UTF-8,开始用iconv()后来改用mb_detect_encoding().2.就是正则了,获取图片等等。获取新闻的调试页面

[2]新闻

 代码特别乱,就不献丑。