如何初始化 Nokogiri::XML::Element

Jua*_*tas 1 ruby nokogiri

我想Nokogiri::XML::Element使用以下方法初始化一个对象:

html = '<a href="https://example.com">Link</a>'
Nokogiri::XML::Element.new(html)
Run Code Online (Sandbox Code Playgroud)

但目前我必须这样做:

Nokogiri::HTML::DocumentFragment.parse(html).children.last
Run Code Online (Sandbox Code Playgroud)

有没有更好的办法?

eng*_*nky 5

Nokogiri提供make方法 ( Nokogiri::make) 作为创建 a 的便捷方法,DocumentFragment并且代码与您现在所做的几乎相同:

def make input = nil, opts = {}, &blk
  if input
    Nokogiri::HTML.fragment(input).children.first
  else
    Nokogiri(&blk)
  end
end
Run Code Online (Sandbox Code Playgroud)

例子:

html = '<a href="https://example.com">Link</a>'
require 'nokogiri'
Nokogiri.make(html)
#=> #<Nokogiri::XML::Element:0x2afe5af3a04c name="a" attributes=
#    [#<Nokogiri::XML::Attr:0x2afe5ac33efc name="href" value="https://example.com">] 
#     children=[#<Nokogiri::XML::Text:0x2afe5ac32408 "Link">]>
Run Code Online (Sandbox Code Playgroud)

其他选项包括

Nokogiri(html).first_element_child
Nokogiri.parse(html).first_element_child
Run Code Online (Sandbox Code Playgroud)