繁体   English   中英

PHP解析器刮取数据错误

[英]PHP parser to scrape data error

我正在尝试编写一个PHP解析器,以从ratemyprofessor.com收集教授评论。 每个教授都有一个页面,页面上有所有评论,我想解析每个教授的网站并将评论提取到txt文件中。 到目前为止,这是我所拥有的,但是在运行它时,它不能正确执行,因为输出txt文件仍然为空。 可能是什么问题?

<?php     
set_time_limit(0);

$domain = "http://www.ratemyprofessors.com";
$content = "div id=commentsection";
$content_tag = "comment";
$output_file = "reviews.txt";
$max_urls_to_check = 400;
$rounds = 0;
$reviews_stack = array();
$max_size_domain_stack = 10000;
$checked_domains = array();


while ($domain != "" && $rounds < $max_urls_to_check) {
    $doc = new DOMDocument();
    @$doc->loadHTMLFile($domain);
    $found = false;


    foreach($doc->getElementsByTagName($content_tag) as $tag) {
        if (strpos($tag->nodeValue, $content)) {
            $found = true;
            break;
        }
    }

    $checked_domains[$domain] = $found;
    foreach($doc->getElementsByTagName('a') as $link) {
        $href = $link->getAttribute('href');
        if (strpos($href, 'http://') !== false && strpos($href, $domain) === false) {
            $href_array = explode("/", $href);

            if (count($domain_stack) < $max_size_domain_stack &&
                $checked_domains["http://".$href_array[2]] === null) {
                array_push($domain_stack, "http://".$href_array[2]);
            }
        };
    }


    $domain_stack = array_unique($domain_stack);
    $domain = $domain_stack[0];
    unset($domain_stack[0]);
    $domain_stack = array_values($domain_stack);
    $rounds++;
}

$found_domains = "";
foreach ($checked_domains as $key => $value) {
    if ($value) {
        $found_domains .= $key."\n";
    }
}


file_put_contents($output_file, $found_domains); 
?>

到目前为止,这是我所拥有的,但是在运行它时,它不能正确执行,因为输出txt文件仍然为空。 可能是什么问题?

由于缺少数组变量初始化,因此它提供了空输出。

  1. 主要部分。 添加变量的初始化:

     $domain_stack = array(); // before while ($domain != ...... ) 
  2. 额外。 修正其他警告和注意事项:

     // change this $checked_domains["http://".$href_array[2]] === null // into !isset($checked_domains["http://".$href_array[2]]) // another line // check if key exists if (isset($domain_stack[0])) { $domain = $domain_stack[0]; unset($domain_stack[0]); } 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM