页面抓取和正则表达式在应该给出的结果时没有给出任何结果


Page scraping and regex give no results when they should

我有一个基于 wp 的小脚本,它可以抓取网页并使用 preg_match_all() 计算 4 个关键字的出现次数。

这是我知道包含关键字的 url 的代码:

<?php
$url ='http://www.leggioggi.it/2013/08/16/i-tre-amici-discutono-di-servizio-sanitario-casuale-e-differenze-nord-sud/';
$response = wp_remote_get($url);
    $the_body = wp_remote_retrieve_body($response);
    //echo htmlentities($the_body);
    $matches = array();
    $matches_count = preg_match_all("/gravidanz|preconcezional|prenatal|concepimento/i", $the_body, $matches);
var_dump ($matches_count);
var_dump ($matches);
?>

我遇到了一些奇怪的问题。在某些页面上,我得到零匹配,即使我知道这些页面包含关键字。我注意到对于这些页面,取消注释该行echo htmlentities($the_body);可以解决问题。如果我再次评论它,奇怪的是又回来了。

我的猜测是涉及一些缓存机制。

PS:代码不是写在模板文件上,而是写在 pods 框架页面中。

更新:我在 htmlentities 行之后放了一个var_dump($the_body);。这种行为很有趣。如果回显htmlentities($the_body);被注释掉var_dump($the_body);返回一个空字符串;如果同一行处于活动状态,则var_dump($the_body);返回整个页面 HTML。所以我真的不明白发生了什么!

解决:我检查了 $response var(我的坏主意没有考虑它),我发现当确实存在远程服务器错误时,wp_remote_get() 返回的响应中报告了该错误。这是我得到的:

object(WP_Error)#30 (2) {
  ["errors"]=>
  array(1) {
    ["http_request_failed"]=>
    array(1) {
      [0]=>
      string(69) "Operation timed out after 5000 milliseconds with 25692 bytes received"
    }
  }
  ["error_data"]=>
  array(0) {
  }
}

我检查了$response var(我的不好没有考虑它),我发现确实存在远程服务器错误,该错误在 wp_remote_get() 返回的响应中报告。这是我得到的:

object(WP_Error)#30 (2) {
  ["errors"]=>
  array(1) {
    ["http_request_failed"]=>
    array(1) {
      [0]=>
      string(69) "Operation timed out after 5000 milliseconds with 25692 bytes received"
    }
  }
  ["error_data"]=>
  array(0) {
  }
}

所以它解决了。我只需要检查 http 错误并重复请求有限的次数,如果没有给出正确的响应,请忽略资源。