如何从评论的 HTML 标签中提取文本

How to extract text from commented HTML tag

我有一个用 Nokogiri 解析过的页面,但我需要从注释标签中获取文本。 HTML 如下:

<div class="parent">
  <div class="child">
    <span class="visible"> hello </span>
    <!-- <span class="commented"> hi </span> -->
  </div>
</div>

假设我将页面作为 Nokogiri page 对象,这是我尝试过的方法,但它给了我 0

page.xpath("//div[@class='parent']/div[@class='child']/comment()").each {|comment| comment.text }

运行:

page.xpath("//div[@class='parent']/div[@class='child']/comment()")

给出:

[#<Nokogiri::XML::Comment:0x3fe466d8d634 " <span class=\"commented\">hi  </span> ">]

我不知道如何获取 hi 文本。

我不是 Nokogiri 专家,但类似的方法似乎有效

comment_node = Nokogiri::HTML(page.at("//div[@class='parent']/div[@class='child']/comment()").text)
comment_node.text.strip
 => "hi"