Is it possible to select HTML comments using QueryPath?

依然范特西╮ 提交于 2020-01-03 01:58:20

问题


I see this is possible using jQuery, but how can it be done in QueryPath?

Selecting HTML Comments with jQuery

If not, can anyone suggest an HTML parser that can select comments?


回答1:


QueryPath comes with an extension called QPXML that has several add-on methods. One of these is comment().

To use it, simply include it in your script:

include 'QueryPath/QueryPath.php';
include 'QueryPath/Extensions/QPXML.php';

htmlqp($html, $selector)->comment();

This will retrieve the first comment attached to the presently selected node(s).

If you have a really sophisticated set of comments all within the same nodes, you can do something like this:

$nodes = $qp->get();
foreach ($nodes as $node) {
   foreach ($node->childNodes as $child) {
      if ($child->nodeType == XML_COMMENT_NODE) {
         // $child is a comment.
         print $child->textContent;
      }
   }
}

This is a little uglier, but it gives better access to cases where one element has a lot of comments in it.




回答2:


To get ALL comments of HTML page via querypath :

    function  getAllComments($node) {
        if ($node->hasChildNodes()) {
            foreach ($node->childNodes as $child) {
                $this->getAllComments($child);
                if ($child->nodeType == XML_COMMENT_NODE) {
                    echo  $child->textContent;
                }
            }

        }
    }

    $html = $qp->get() ;
    getAllComments($html[0]);


来源:https://stackoverflow.com/questions/7039817/is-it-possible-to-select-html-comments-using-querypath

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!