我正在尝试在h3
代码后添加一行文字。
我的首发HTML是:
<h3>hi</h3>
没有其他标签或文档类型。我希望我的结束HTML看起来像这样:
<h3>hi</h3>
{% include 'tester-credit-button' %}
我尝试了以下内容:
page = Nokogiri::HTML::DocumentFragment.parse("my_page.html")
title = page.at_css("h3")
#tried this first
title.children.after("\n{% include 'tester-credit-button' %}")
#then this
title << "\n{% include 'tester-credit-button' %}"
#then this
title.after("\n{% include 'tester-credit-button' %}")
#then this
text_node = Nokogiri::XML::Text.new("\n{% include 'tester-credit-button' %}"
, page)
title.add_child(text_node)
答案 0 :(得分:-2)
你做得太难了:
require 'nokogiri'
doc = Nokogiri::HTML::DocumentFragment.parse('<h3>hi</h3>')
doc.at('h3').next = "\n{% include 'tester-credit-button' %}"
puts doc.to_html
# >> <h3>hi</h3>
# >> {% include 'tester-credit-button' %}
返回您的代码......
page = Nokogiri::HTML::DocumentFragment.parse("my_page.html")
错了。您可以使用以下方法轻松测试:
page.to_html # => "my_page.html"
在the documentation中,当它说&#34; tags
&#34;这意味着你必须传入一些HTML或XML:
page = Nokogiri::HTML::DocumentFragment.parse("<p><span>foo</span></p>")
page.to_html # => "<p><span>foo</span></p>"
我建议研究HTML和XML的结构,因为您的实验表明您不了解解析文档的节点,可能的类型以及他们的孩子和兄弟姐妹的想法。 Nokogiri的教程将有所帮助,在SO上搜索标签并阅读各种问题和答案也会有所帮助。一旦你掌握了这个概念,Nokogiri的功能强大且易于使用。