7

parent_element_h1変数とを埋めようとしていますparent_element_h2Nokogiriを使用して必要な情報をこれらの変数に取得するのを手伝ってくれる人はいますか?

require 'rubygems'
require 'nokogiri'

value = Nokogiri::HTML.parse(<<-HTML_END)
  "<html>
    <body>
      <p id='para-1'>A</p>
      <div class='block' id='X1'>
        <h1>Foo</h1>
        <p id='para-2'>B</p>
      </div>
      <p id='para-3'>C</p>
      <h2>Bar</h2>
      <p id='para-4'>D</p>
      <p id='para-5'>E</p>
      <div class='block' id='X2'>
        <p id='para-6'>F</p>
      </div>
    </body>
  </html>"
HTML_END

parent = value.css('body').first

# start_here is given: A Nokogiri::XML::Element of the <div> with the id 'X2
start_here = parent.at('div.block#X2')

# this should be a Nokogiri::XML::Element of the nearest, previous h1.
# in this example it's the one with the value 'Foo'
parent_element_h1 = 

# this should be a Nokogiri::XML::Element of the nearest, previous h2. 
# in this example it's the one with the value 'Bar'
parent_element_h2 =

注意:start_here要素はドキュメント内のどこにでもある可能性があります。HTML データは単なる例です。つまり、ヘッダー<h1>およびは、 の兄弟または の兄弟の子である<h2>可能性があります。start_herestart_here

<h1>次の再帰的メソッドは出発点としては適切ですが、 の兄弟の子であるため機能しませんstart_here

def search_element(_block,_style)
  unless _block.nil?
    if _block.name == _style
      return _block
    else
      search_element(_block.previous,_style)
    end
  else
    return false
  end
end

parent_element_h1 = search_element(start_here,'h1')
parent_element_h2 = search_element(start_here,'h2')

答えを受け入れた後、私は自分の解決策を思いつきました。それは魔法のように機能し、かなりクールだと思います。

4

6 に答える 6

10

私が取るアプローチ (問題を理解している場合) は、XPath または CSS を使用して、「start_here」要素と検索対象の親要素を検索することです。次に、親から開始して再帰的にツリーをたどり、「start_here」要素にヒットすると停止し、途中でスタイルに一致する最後の要素を保持します。

何かのようなもの:

parent = value.search("//body").first
div = value.search("//div[@id = 'X2']").first

find = FindPriorTo.new(div)

assert_equal('Foo', find.find_from(parent, 'h1').text)
assert_equal('Bar', find.find_from(parent, 'h2').text) 

再帰FindPriorToを処理する単純なクラスは次のとおりです。

class FindPriorTo
  def initialize(stop_element)
    @stop_element = stop_element
  end

  def find_from(parent, style)
    @should_stop = nil
    @last_style  = nil

    recursive_search(parent, style)
  end

  def recursive_search(parent, style)
    parent.children.each do |ch|
      recursive_search(ch, style)
      return @last_style if @should_stop

      @should_stop = (ch == @stop_element)
      @last_style = ch if ch.name == style
    end

    @last_style    
  end

end

このアプローチが十分にスケーラブルでない場合は、recursive_search再帰を使用しないように を書き換えて最適化し、探している両方のスタイルを渡し、最後に見つかったものを追跡することができるため、木を余分に横断する。

また、ドキュメントが解析されるときに Node にフックするモンキー パッチを試してみるといいと思いますが、それはすべて C で記述されているようです。おそらく、ネイティブの Ruby SAX パーサーを備えた Nokogiri 以外のものを使用したほうがよいかもしれません (おそらくREXML )、または速度が本当に重要な場合は、Xerces などを使用して C/C++ で検索部分を実行します。ただし、これらが HTML の解析にどれだけうまく対処できるかはわかりません。

于 2009-03-18T15:08:07.277 に答える
3

私がこれに出くわしたのは数年遅かったと思いますが、他のすべてのソリューションは複雑すぎるため、投稿せざるを得ないと感じました.

XPath を使用した単一のステートメントです。

start = doc.at('div.block#X2')

start.at_xpath('(preceding-sibling::h1 | preceding-sibling::*//h1)[last()]')
#=> <h2>Foo</h2>    

start.at_xpath('(preceding-sibling::h2 | preceding-sibling::*//h2)[last()]')
#=> <h2>Bar</h2>

これは、直接の前の兄弟または前の兄弟の子供のいずれかに対応します。どちらが一致するかに関係なく、last()述語により、最も近い前の一致が得られます。

于 2014-03-11T22:28:33.183 に答える
2

たぶん、これでうまくいくでしょう。パフォーマンスについてはよくわかりません。また、考えていない場合があるかもしれません。

def find(root, start, tag)
    ps, res = start, nil
    until res or (ps == root)
        ps  = ps.previous || ps.parent
        res = ps.css(tag).last
        res ||= ps.name == tag ? ps : nil
    end
    res || "Not found!"
end

parent_element_h1 =  find(parent, start_here, 'h1')
于 2009-04-01T09:11:27.560 に答える
0

これは、兄弟または別の兄弟の子であるかどうかに関係なく、再帰的な方法を使用してすべての要素を解析するための再帰的な方法を使用した、私自身の解決策です(これについては同僚に感謝します!)。

require 'rubygems'
require 'nokogiri'

value = Nokogiri::HTML.parse(<<-HTML_END)
  "<html>
    <body>
      <p id='para-1'>A</p>
      <div class='block' id='X1'>
        <h1>Foo</h1>
        <p id='para-2'>B</p>
      </div>
      <p id='para-3'>C</p>
      <h2>Bar</h2>
      <p id='para-4'>D</p>
      <p id='para-5'>E</p>
      <div class='block' id='X2'>
        <p id='para-6'>F</p>
      </div>
    </body>
  </html>"
HTML_END

parent = value.css('body').first

# start_here is given: A Nokogiri::XML::Element of the <div> with the id 'X2
@start_here = parent.at('div.block#X2')

# Search for parent elements of kind "_style" starting from _start_element
def search_for_parent_element(_start_element, _style)
  unless _start_element.nil?
    # have we already found what we're looking for?
    if _start_element.name == _style
      return _start_element
    end
    # _start_element is a div.block and not the _start_element itself
    if _start_element[:class] == "block" && _start_element[:id] != @start_here[:id]
      # begin recursion with last child inside div.block
      from_child = search_for_parent_element(_start_element.children.last, _style)
      if(from_child)
        return from_child
      end
    end
    # begin recursion with previous element
    from_child = search_for_parent_element(_start_element.previous, _style) 
    return from_child ? from_child : false
  else
    return false
  end
end

# this should be a Nokogiri::XML::Element of the nearest, previous h1.
# in this example it's the one with the value 'Foo'
puts parent_element_h1 = search_for_parent_element(@start_here,"h1")

# this should be a Nokogiri::XML::Element of the nearest, previous h2. 
# in this example it's the one with the value 'Bar'
puts parent_element_h2 = search_for_parent_element(@start_here,"h2")

ルビースクリプトのようにコピーして貼り付けて実行できます。

于 2009-04-22T16:46:24.853 に答える
-1

要素間の関係がわからない場合は、次の方法で検索できます (ドキュメント内の任意の場所)。


# html code
text = "insert your html here"
# get doc object
doc = Nokogiri::HTML(text)
# get elements with the specified tag
elements = doc.search("//your_tag")

ただし、フォームを送信する必要がある場合は、mechanize を使用する必要があります。


# create mech object
mech = WWW::Mechanize.new
# load site
mech.get("address")
# select a form, in this case, I select the first form. You can select the one you need 
# from the array
form = mech.page.forms.first
# you fill the fields like this: form.name_of_the_field
form.element_name  = value
form.other_element = other_value
于 2009-03-18T19:40:12.787 に答える
-1

HTML::ElementCSS セレクターを使用して、ノコギリの子孫を検索できます。メソッドを使用して祖先をたどることができます.parent

parent_element_h1 = value.css("h1").first.parent
parent_element_h2 = value.css("h2").first.parent
于 2009-03-25T19:15:37.240 に答える