如何抓取关键字在百度搜索的排名

时间:2024-02-17 15:15:03

今天想做一个网站上的关键字在百度搜索中的排名。效果如图:

功能很简单,输入关键字,输入域名,点击搜索,就会出现下图:

现在把代码贴出来,希望可以帮助到好学的朋友。

View Code
    <?php
        function search($keyword,$url,$page = 1){
        static $px = 0;
        $rsState = false;
        
        $enKeyword = urlencode($keyword);
        $firstRow = ($page - 1) * 10;
        
        if($page > 10){
        exit(\'10页之内没有该网站排名..end\');
        }
        $contents = file_get_contents("http://www.baidu.com/s?wd=$enKeyword&&pn=$firstRow");
        preg_match_all(\'/<table[^>]*?class="result"[^>]*>[\s\S]*?<\/table>/i\',$contents,$rs);
        foreach($rs[0] as $k=>$v){
        $px++;
        if(strstr($v,$url)){
        $rsState = true;
        preg_match_all(\'/<h3[\s\S]*?(<a[\s\S]*?<\/a>)/\',$v,$rs_t);
        echo \'当前 "\' . $url . \'" 在百度关键字 "\' . $keyword . \'" 中的排名为:\' . $px;
        echo \'<br>\';
        echo \'第\' . $page . \'页;第\' . ++$k . "个<a target=\'_blank\' href=\'http://www.baidu.com/s?wd=$enKeyword&&pn=$firstRow\'>进入百度</a>";
        echo \'<br>\';
        //var_dump($rs_t[1][0]) ;
        $rs_t[1][0] = iconv(\'UTF-8\',\'GBK\',$rs_t[1][0]);
        echo $rs_t[1][0];
        break;
        }
        }
        unset($contents);
        if($rsState === false){
        search($keyword, $url,++$page);
        }
        }
        if(isset($_POST[\'submit\'])){
        $time = explode(\' \',microtime());
        $start = $time[0] + $time[1];
        $url = $_POST[\'url\'];
        if( count(explode(\'.\',$url)) <= 2){
        $url = ltrim($url,\'http://\');
        $url = \'www.\' . $url;
        }
        search($_POST[\'keyword\'],$url);
        $endtime = explode(\' \',microtime());
        $end = $endtime[0] + $endtime[1];
        echo "<br/>";
        echo \'程序运行时间: \';
        echo $end - $start;
        }
    
    ?>
    
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
    <title>抓取排名</title>
    </head>
    <body>
    <form action="" method="post">
    <ul>
    <li>
    <span>关键字:</span><input type="text" name="keyword" >
    </li>
    <li>
    <span>url地址:</span><input type="text" name="url">
    </li>
    <li>
    <input type="submit" name="submit" value="搜索">
    </li>
    </ul>
    </form>
    </body>
    </html>

 

当然,功能还不完善,例如:暂时不支持回车搜索,手动输入域名太麻烦等等。。。

我会后续完善的。

加油~!