如何提取 html 注释和节点包含的所有 html


How to extract html comments and all html contained by node?

我正在创建一个小的网络应用程序来帮助我管理和分析我网站的内容,cURL 是我最喜欢的新玩具。 我已经弄清楚了如何提取有关各种元素的信息,如何找到具有某个类的所有元素等,但是我遇到了两个问题(见下文)。 我希望有一些漂亮的 xpath 答案,但如果我不得不求助于正则表达式,我想没关系。 虽然我对正则表达式不是很好,所以如果你认为这是要走的路,我会感谢例子......

相当标准的起点:

$ch = curl_init();
    curl_setopt($ch, CURLOPT_USERAGENT, $userAgent);
    curl_setopt($ch, CURLOPT_URL,$target_url);
    curl_setopt($ch, CURLOPT_FAILONERROR, true);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_AUTOREFERER, true);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    $html = curl_exec($ch);
    if (!$html) {
        $info .= "<br />cURL error number:" .curl_errno($ch);
        $info .= "<br />cURL error:" . curl_error($ch);
        return $info;
    }
    $dom = new DOMDocument();
    @$dom->loadHTML($html);
    $xpath = new DOMXPath($dom);

和信息提取,例如:

// iframes
    $iframes = $xpath->evaluate("/html/body//iframe");
    $info .= '<h3>iframes ('.$iframes->length.'):</h3>';
    for ($i = 0; $i < $iframes->length; $i++) {
        // get iframe attributes
        $iframe = $iframes->item($i);
        $framesrc = $iframe->getAttribute("src");
        $framewidth = $iframe->getAttribute("width");
        $frameheight = $iframe->getAttribute("height");
        $framealt = $iframe->getAttribute("alt");
        $frameclass = $iframe->getAttribute("class");
        $info .= $framesrc.'&nbsp;('.$framewidth.'x'.$frameheight.'; class="'.$frameclass.'")'.'<br />';
    }
问题

/问题:

  1. 如何提取 HTML 注释?

    我不知道如何识别评论——它们是节点,还是完全是其他东西?

  2. 如何获取div的全部内容,包括子节点? 因此,如果div 包含一个图像和几个 href,它会找到它们并将其作为 HTML 块全部交还给我。

注释节点应该很容易在 XPath 中找到,使用 comment() 测试,类似于text()测试:

$comments = $xpath->query('//comment()'); // or another path, as you prefer

它们是标准节点:这是DOMComment类的手动条目。


对于你的另一个问题,这有点棘手。 最简单的方法是将 saveXML() 与其可选的 $node 参数一起使用:

$html = $dom->saveXML($el);  // $el should be the element you want to get 
                             // the HTML for

对于 HTML 注释,快速方法是:

 function getComments ($html) {
     $rcomments = array();
     $comments = array();
     if (preg_match_all('#<'!--(.*?)-->#is', $html, $rcomments)) {
         foreach ($rcomments as $c) {
             $comments[] = $c[1];
         }
         return $comments;
     } else {
         // No comments matchs
         return null;
     }
 }
那个

正则表达式
's*<!--['s'S]+?-->对你有帮助。

在正则表达式测试中

对于注释,您正在寻找递归正则表达式。例如,要摆脱 html 注释:

preg_replace('/<!--(?(?=<!--)(?R)|.)*?-->/s',$yourHTML);

要找到它们:

preg_match_all('/(<!--(?(?=<!--)(?R)|.)*?-->)/s',$yourHTML,$comments);