specialnot 2015-12-02 16:40:51 6116次浏览 1条评论 6 0 0

背景:百度收录了很多以前网站、域名的页面,这些页面是无效的,需要汇总出来,然后向百度提交。但是手动汇总很麻烦,所以我就做了个小程序,抓取百度搜索结果,然后判断页面是否能够访问,不能访问就写入文件。

相关采集技术见:YII2网站采集

<?php
namespace console\controllers;

use Goutte\Client;
use yii\console\Controller;

class UrlSpiderController extends Controller{
    //采集交易所公告
    public function actionRun(){
        @set_time_limit(-1);
        $arrays = [];
        $client = new Client();
        //循环获取百度搜索网址,并对分页进行处理
        for($i=0;$i<=75;$i++){
            $j = 10*$i;
            $url = 'http://www.baidu.com/s?wd=site%3Aqhmoney.cn&pn='.$j.'&oq=site%3Aqhmoney.cn&ie=utf-8&f=3&usm=1&rsv_pq=88108cd80002d6be&rsv_t=3a40aT%2B5WIgyrNJJIOxOn42wx795GCIQHic27ofL0HTGhDWcfXZTvulEmBU';
            //采集网址列表
            $crawler = $client->request('GET', $url);
            $crawler->filter('#content_left .t a')->each(function ($node) use(&$arrays){
                if(count($node)){
                    $href = $node->attr('href');
                    $h = $this->getrealurl($href);
                    $arrays[] = $h;
                }
            });
        }
        //判断地址是否可用
        foreach($arrays as $url){
            $handle = get_headers($url);
            if($handle){
                if($handle['0'] == 'HTTP/1.1 404 Not Found'){
                    file_put_contents(\Yii::$app->getBasePath().'/url.txt',$url.PHP_EOL,FILE_APPEND);
                }
            }
        }

    }

    //解析百度地址
    function getrealurl($url){
        $header = get_headers($url,1);
        if (strpos($header[0],'301') || strpos($header[0],'302')) {
            if(is_array($header['Location'])) {
                return $header['Location'][count($header['Location'])-1];
            }else{
                return $header['Location'];
            }
        }else {
            return $url;
        }
    }

}
您需要登录后才可以评论。登录 | 立即注册