ruby – 从inner_html中删除评论
发布时间:2020-12-16 19:17:11 所属栏目:百科 来源:网络整理
导读:我有一些使用Nokogiri的代码,我试图获取inner_html而不收到评论. html = Nokogiri::HTML(open(@sql_scripts_url[1])) #using first value of the arrayhtml.css('td[class="ms-formbody"]').each do |node| puts node.inner_html # prints commentsend 解决
我有一些使用Nokogiri的代码,我试图获取inner_html而不收到评论.
html = Nokogiri::HTML(open(@sql_scripts_url[1])) #using first value of the array html.css('td[class="ms-formbody"]').each do |node| puts node.inner_html # prints comments end 解决方法
由于您未提供任何示例HTML或所需输出,因此这是一般解决方案:
您可以使用 require 'nokogiri' doc = Nokogiri.XML('<r><b>hello</b> <!-- foo --> world</r>') p doc.inner_html #=> "<b>hello</b> <!-- foo --> world" doc.xpath('//comment()').remove p doc.inner_html #=> "<b>hello</b> world" 请注意,上述内容会破坏性地修改文档以删除注释.如果您希望保持原始文档不被修改,您可以选择这样做: class Nokogiri::XML::Node def inner_html_reject(xpath='.//comment()') dup.tap{ |shadow| shadow.xpath(xpath).remove }.inner_html end end doc = Nokogiri.XML('<r><b>hello</b> <!-- foo --> world</r>') p doc.inner_html_reject #=> "<r><b>hello</b> world</r>" p doc.inner_html #=> "<r><b>hello</b> <!-- foo --> world</r>" 最后请注意,如果您不需要标记,只要求文本本身不包含HTML注释: p doc.text #=> "hello world" (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |