4

是的,我已经建立了一个网络爬虫。它扫描链接、标题和元描述。它扫描链接并将它们保存在 $link 中。它扫描链接的标题并将它们保存在 newArray 中的 [title] 中。现在在这个数组中,我想让它知道如果没有元标记,它可以扫描第一个 p 标记并使用它。唯一的问题是它似乎根本没有保存任何信息。

function getMetas($link) {
$str1 = file_get_contents($link);    

    if (strlen($str1)>0) {
 preg_match_all( '/<meta.*?name=("|\')description("|\').*?content=("|\')(.*?)("|\')/i', $str1, $description);
   if (count($description) > 1) {
    return $description[4];   
   }


   }
 return '';
   if ($description == '') {
$html = file_get_contents($link);    
preg_match('%(<p[^>]*>.*?</p>)%i', $html, $re);
$res = get_custom_excerpt($re[1]);
echo "\n";
echo $res;
echo "\n";

}

    function get_custom_excerpt($return, $option = 30, $sentance = false) {
    $marks = Array(".","!","?");

   $return = strip_tags($return);

  if($sentance == true) {
$start = implode(" ", array_slice(preg_split("/\s+/", $return), 0, $option ));
$start .= ' ';
$end = implode(" ", array_slice(preg_split("/\s+/", $return), $option));

$cut = Array();
foreach($marks AS $m => $mark){
  $mark = strpos($end, $mark);
  if($mark != false) $cut[$m] = $mark;
}

if($cut[0] != "")
  $chop = min($cut);
    else
      $chop = $option;
$rest = substr($end, 0, $chop);

$key = array_search($chop, $cut);

$return = $start.$rest;

   }else{
$return = implode(" ", array_slice(preg_split("/\s+/", $return), 0, $option));
   }
  $return .= $marks[$key];

  return $return; 
   }  

   }


 $output = Array();

 foreach ($links as $thisLink) {
 $output[] = array("link" => $thisLink, "title" => Titles($thisLink), "description" => getMetas($thisLink), getMetas($res));
 } 
  print_r($output);
4

1 回答 1

2

您的正则表达式可能不起作用。属性可能不是您想要的顺序。它可能是<meta name="" content=""><meta content="" name="">

为什么不使用 XML 解析器?大多数 HTML 都足以用于解析。

请看一下PHP Parse HTML 代码

于 2012-09-24T07:29:53.863 回答