【问题标题】:php spider script not workingphp蜘蛛脚本不起作用
【发布时间】:2012-09-17 00:52:00
【问题描述】:

我一直在使用以下脚本为我的客户网站创建站点地图。问题是它不适用于每个站点。我发现,godaddy 上托管的许多(如果不是全部)网站都没有蜘蛛。如果有人可以在我的脚本中看到错误或知道导致错误的原因,我将非常感谢您的帮助。

提前致谢

set_time_limit(0);
class spider_man
{
var $url;
var $limit;
var $cache;
var $crawled;
var $banned_ext;
var $domain;

function spider_man( $url, $banned_ext, $limit ){
    $this->domain = $url;
    $this->url = 'http://'.$url ;
    $this->banned_ext = $banned_ext ;
    $this->limit = $limit ;
    if( !fopen( $this->url, "r") ) return false;
    else $this->_spider($this->url);
}

function _spider( $url ){
    $this->cache = @file_get_contents( urldecode( $url ) );
    if( !$this->cache ) return false;
    $this->crawled[] = urldecode( $url ) ;
    preg_match_all( "#href=\"(https?://[&=a-zA-Z0-9-_./]+)\"#si", $this->cache, $links );
    if ( $links ) :
        foreach ( $links[1] as $hyperlink ){                
            if(strpos($hyperlink,$this->domain)===false){ break; }
            else{
                $this->limit--;
                if( ! $this->limit ) return;
                if( $this->is_valid_ext( trim( $hyperlink ) ) and !$this->is_crawled( $hyperlink ) ) :
                $this->crawled[] = $hyperlink;
                echo "Crawling $hyperlink<br />\n";
                unset( $this->cache );
                $this->_spider( $hyperlink );
                endif;
            }
        }
    endif;
}

function is_valid_ext( $url ){   
    foreach( $this->banned_ext as $ext ){
        if( $ext == substr( $url, strlen($url) - strlen( $ext ) ) ) return false;
    }
    return true;
}
function is_crawled( $url ){
    return in_array( $url, $this->crawled );
}
}

$banned_ext = array(".dtd",".css",".xml",".js",".gif",".jpg",".jpeg",".bmp",".ico",".rss",".pdf",".png",".psd",".aspx",".jsp",".srf",".cgi",".exe",".cfm");

$spider = new spider_man( 'domain.com', $banned_ext, 100 );
print_r( $spider->crawled );

【问题讨论】:

  • 问题出在哪里?
  • 当您尝试在 GoDaddy 网站上运行它时会发生什么?
  • 网站不返回任何网址。它只是返回一个空数组
  • @James 使用 error_reporting 并从 fgc 函数中删除 @

标签: php web-crawler


【解决方案1】:

当您使用 fopen() 的 file_get_contents() 访问站点时,您不会发送 AGENT 或 REFERRER 或其他标头信息。很明显这是一个自动化脚本。

您需要查看使用 fopen 发送上下文(check the docs 并阅读上下文部分),或者更好的是使用CURL。这允许您设置代理和引荐标头以模拟浏览器。

【讨论】:

    猜你喜欢
    • 2014-03-06
    • 2020-11-08
    • 1970-01-01
    • 1970-01-01
    • 2018-12-02
    • 2017-07-19
    • 1970-01-01
    • 2013-11-08
    • 2011-02-20
    相关资源
    最近更新 更多