微信实现新闻抓取(更新啦)

Posted by Struggle Blog on May 30, 2016

新闻抓取

  • 基本操作是

    1. 找到指定网页

    2. 查看源代码,确定抓取的范围

    3. 修改代码,并上传从而实现内容抓取

代码实现(以华中科技大学为例)

<?php

		$url="http://www.hust.edu.cn/tzgg_150/list.htm";//这个链接换成你想抓取新闻的链接

		

		$ch=curl_init($url);

		curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);

		$str=curl_exec($ch);

		curl_close($ch);

		

		//echo $str;  //显示整个页面

		//------------------下面是更新的部分------------------

        /*

        我们在查看源代码时看html中是否有<meta charset="XXX">这类话,然后复制这个XXX

        */

        $char="XXX";

		$str=mb_convert_encoding($str, "utf-8",$char);

        

		$start='<ul class="wp_article_list">';  //开始的内容

		$end='<div id="wp_paging_w7">';  		//结束的内容

		

		$wzs=strpos($str,$start);				//开始的位置

		$wze=strpos($str,$end);					//结束的位置

		

		$len=$wze-$wzs;						//内容的总长度

		

		$content=substr($str,$wzs,$len);  	//目的:只显示我们需要的那一部分

		echo $content;

?>

保存上面的代码到news.php,修改后上传到你服务器,比如我的是http://hi.wxhand.cn/news/news.php

全部过程如下(GIF加载会比较慢哦,耐心看)

chaxun5

下面是新增部分

直接将下面代码放在你news.php最后面,同时注意看注释。

		//下面我们开始尝试匹配标题和链接
		echo "<br>";
		$content=preg_replace("/[\t\n\r]+/","",$content);
		$pattern='/<a href=\'(.*?)\'.*?>(.*?)<\/a>/i';

		/* 或者用下面这个,主要是根据你所要匹配的内容是<a href=""></a>还是<a href=''></a>,来选择

		$pattern='/<a href=\"(.*?)\".*?>(.*?)<\/a>/i';

		*/

		preg_match_all($pattern, $content, $matches);

			for($i=0;$i<8;$i++){
				$url = $matches[1][$i];
				echo $url."->";
				$title = $matches[2][$i];
				echo $title ;
				echo "<br>";
			}

如果发现有新的内容,则说明,上面这段代码匹配成功。

下面我们去弄微信上的接口,取名为newsapi.php,复制下面代码,并修改相关内容。

<?php
// 高校新闻抓取
// 助梦者(573149038)
define("TOKEN", "weixin");                    //token自己改


$wechatObj = new wechatCallbackapiTest();
if (!isset($_GET['echostr'])) {
	$wechatObj->responseMsg();
}else{
    $wechatObj->valid();
}

class wechatCallbackapiTest
{
    public function valid()
    {
        $echoStr = $_GET["echostr"];
        if($this->checkSignature()){
            echo $echoStr;
            exit;
        }
    }

    private function checkSignature()
    {
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];
        $token = TOKEN;
        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr);
        $tmpStr = implode($tmpArr);
        $tmpStr = sha1($tmpStr);

        if($tmpStr == $signature){
            return true;
        }else{
            return false;
        }
    }

    public function responseMsg()
    {
        $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
        if (!empty($postStr)){
            $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
            $RX_TYPE = trim($postObj->MsgType);

            //用户发送的消息类型判断
            switch ($RX_TYPE)
            {
                case "text":
                    $result = $this->receiveText($postObj);
                    break;
                case "image":
                    $result = $this->receiveImage($postObj);
                    break;
                case "voice":
                    $result = $this->receiveVoice($postObj);
                    break;
                case "video":
                    $result = $this->receiveVideo($postObj);
                    break;
                default:
                    $result = "unknow msg type: ".$RX_TYPE;
                    break;
            }
            echo $result;
        }else {
            echo "";
            exit;
        }
    }
    private function receiveText($object)
    {
        $keyword = trim($object->Content);
		$openid=$object->FromUserName;
		if($keyword == "校园新闻") //keyword自己改 
		 {
			 $news = array();     
			 $jdurl="http://mp.weixin.qq.com/s?__biz=MzA5MjkzODYwMw==&mid=206026721&idx=1&sn=59427fa2b32910c71e015185bf8fe0c6#rd";			
			 //$jdurl 是点击首栏图片后跳转的链接
			$news[] = array('Title'=>'【校园新闻】', 'Description'=>'', 'Picurl'=>'','Url'=>$jdurl);

	 		$url = "http://hi.wxhand.cn/news/news.php";  
	 		//填写你自己的news.php的地址,此时news.php中不需要上面那段尝试匹配的代码
			$ch=curl_init($url);
			curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
			$str=curl_exec($ch);
			curl_close($ch);

			//$str=mb_convert_encoding($str, "utf-8", "gb2312");  //这里是编码转换,如果乱码可以试试

			$str=preg_replace("/[\t\n\r]+/","",$str);
			$pattern='/<a href=\'(.*?)\'.*?>(.*?)<\/a>/i';

			/* 或者用下面这个,主要是根据你所要匹配的内容是<a href=""></a>还是<a href=''></a>,来选择

			$pattern='/<a href=\"(.*?)\".*?>(.*?)<\/a>/i';

			*/

			preg_match_all($pattern, $str, $matches);
			for($i=0;$i<8;$i++){
						$u=$matches[1][$i];		//如果这个$u是个短连接,那么我们需要在下面处理下
						$t=$matches[2][$i];
						
						//$u ='http://www.ujs.edu.cn/'.$u;  //对
						$news[] = array('Title'=>$t , 'Description'=>'', 'PicUrl'=>'','Url'=>$u);
				}
				$result = $this->transmitNews($object, $news);
		}
		return $result;
        
	}

    private function receiveImage($object)
    {
        //回复图片消息 
        $content = array("MediaId"=>$object->MediaId);
        $result = $this->transmitImage($object, $content);;
        return $result;
    }

    /*
     * 回复文本消息
     */
    private function transmitText($object, $content)
    {
        $textTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA[%s]]></Content>
</xml>";
        $result = sprintf($textTpl, $object->FromUserName, $object->ToUserName, time(), $content);
        return $result;
    }
    
    /*
     * 回复图片消息
     */
    private function transmitImage($object, $imageArray)
    {
        $itemTpl = "<Image>
    <MediaId><![CDATA[%s]]></MediaId>
</Image>";

        $item_str = sprintf($itemTpl, $imageArray['MediaId']);

        $textTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[image]]></MsgType>
$item_str
</xml>";

        $result = sprintf($textTpl, $object->FromUserName, $object->ToUserName, time());
        return $result;
    }
    
    /*
     * 回复图文消息
     */
    private function transmitNews($object, $arr_item)
    {
        if(!is_array($arr_item))
            return;

        $itemTpl = "    <item>
        <Title><![CDATA[%s]]></Title>
        <Description><![CDATA[%s]]></Description>
        <PicUrl><![CDATA[%s]]></PicUrl>
        <Url><![CDATA[%s]]></Url>
    </item>
";
        $item_str = "";
        foreach ($arr_item as $item)
            $item_str .= sprintf($itemTpl, $item['Title'], $item['Description'], $item['PicUrl'], $item['Url']);

        $newsTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[news]]></MsgType>
<Content><![CDATA[]]></Content>
<ArticleCount>%s</ArticleCount>
<Articles>
$item_str</Articles>
</xml>";

        $result = sprintf($newsTpl, $object->FromUserName, $object->ToUserName, time(), count($arr_item));
        return $result;
    }
    
  
}
?>


如果仍然有疑问,联系

qqgroup