使用Nokogiri获取倒数第二个脚本结束标记

问题描述 投票:1回答:1

示例代码:

<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]。但是,它将代码放置在标签内。

ruby nokogiri
1个回答
0
投票

有一条CSS规则可“排除”某些元素:not。与first-childlast-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">]>
# ]

如果您需要在文档中插入元素,则可以使用atadd_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>
© www.soinside.com 2019 - 2024. All rights reserved.