【问题标题】:How to use Nokogiri to get the full HTML without any text content如何使用 Nokogiri 获取没有任何文本内容的完整 HTML
【发布时间】:2021-12-11 08:45:36
【问题描述】:

我正在尝试使用 Nokogiri 获取页面的完整 HTML,但删除了所有文本。

我试过这个:

require 'nokogiri'
x = "<html>  <body>  <div class='example'><span>Hello</span></div></body></html>"
y = Nokogiri::HTML.parse(x).xpath("//*[not(text())]").each { |a| a.children.remove }
puts y.to_s

这个输出:

<div class="example"></div>

我也试过不带children.remove 部分运行它:

y = Nokogiri::HTML.parse(x).xpath("//*[not(text())]")
puts y.to_s

然后我得到:

<div class="example"><span>Hello</span></div>

但我真正想要的是:

<html><body><div class='example'><span></span></div></body></html>

【问题讨论】:

    标签: ruby web-scraping xpath html-parsing nokogiri


    【解决方案1】:

    注意:这是一种非常激进的方法。 &lt;script&gt;&lt;style&gt;&lt;noscript&gt; 等标签也有子 text() 节点,其中包含您可能不想根据用例过滤掉的 CSS、HTML 和 JS。

    如果您对已解析的文档进行操作而不是捕获迭代器的返回值,您将能够删除文本节点,然后返回文档:

    require 'nokogiri'
    html = "<html>  <body>  <div class='example'><span>Hello</span></div></body></html>"
    
    # Parse HTML
    doc = Nokogiri::HTML.parse(html)
    
    puts doc.inner_html
    # => "<html>  <body>  <div class=\"example\"><span>Hello</span></div>\n</body>\n</html>"
    
    # Remove text nodes from parsed document
    doc.xpath("//text()").each { |t| t.remove }
    
    puts doc.inner_html
    # => "<html><body><div class=\"example\"><span></span></div></body></html>"
    

    【讨论】:

    • 谢谢你,@ezkl!这非常有帮助。很好奇为什么你说这不是解决问题的好方法?
    • @jayp 我将更新我的答案以反映它确实取决于您的用例,但如果您要将这种确切的方法应用于更复杂的网页,您最终会丢弃子文本节点在&lt;style&gt;&lt;script&gt;&lt;noscript&gt;等功能标签之间
    猜你喜欢
    • 1970-01-01
    • 2010-09-27
    • 2011-06-24
    • 2012-06-04
    • 2019-07-12
    • 2012-11-21
    • 2015-02-13
    • 2020-07-05
    • 1970-01-01
    相关资源
    最近更新 更多