示例代码:
<head>
<script src="first.js"></script>
<script src="second.js"></script>
<!-- How to place some scripts here? -->
<script>
// init load
</script>
</head>
我尝试过这样的代码doc.css('/html/head/script')[-2]
。但是,它将代码放置在标签内。
有一条CSS规则可“排除”某些元素:not
。与first-child
和last-child
结合使用,您可以在head
标签中省略第一个和最后一个脚本:
require 'nokogiri'
doc = <<-DOC
<head>
<script src="Build/UnityLoader.js"></script>
<!-- How to place some scripts here? -->
<script src="second"></script>
<script src="third"></script>
<script>
// init load
</script>
</head>
DOC
p Nokogiri.parse(doc).css('head script:not(:first-child):not(:last-child)')
# [
# #<Nokogiri::XML::Element:0x3fc9d142f4d4 name="script" attributes=[#<Nokogiri::XML::Attr:0x3fc9d142f358 name="src" value="second">]>,
# #<Nokogiri::XML::Element:0x3fc9d142e73c name="script" attributes=[#<Nokogiri::XML::Attr:0x3fc9d142e250 name="src" value="third">]>
# ]
如果您需要在文档中插入元素,则可以使用at
和add_next_sibling
的组合。例如:
require 'nokogiri'
doc = <<-DOC
<head>
<script src="Build/UnityLoader.js"></script>
<!-- How to place some scripts here? -->
<script>
// init load
</script>
</head>
DOC
parsed = Nokogiri.parse(doc)
parsed.at('head script').add_next_sibling('<script src="second"></script>')
p parsed.to_html
# <head>
# <script src="Build/UnityLoader.js"></script>
# <script src="second"></script>
# <!-- How to place some scripts here? -->
# <script>
# // init load
# </script>
# </head>