Как получить ссылки с помощью Mechanize и nokogiri ruby

Учитывая приведенный ниже пример, может ли кто-нибудь показать мне, как я могу использовать Nokogiri и Mechanize, чтобы получить все ссылки под каждым из тегов <h4> в отдельных группах, I.E. все ссылки под:

  1. "какой-то текст"
  2. "еще текст"
  3. "дополнительный текст"
<div id="right_holder">
    <h3><a href="#"><img src="http://example.com" width="11" height="11"></a></h3>
    <br />
    <br />
    <h4><a href="#">Some text</a></h4>
    <a href="#" alt="name of item"><img src="http://some.image.com" class="class1"></a>
    <a href="#" alt="name of item"><img src="http://some.image.com" class="class1"></a>
    <a href="#" alt="name of item"><img src="http://some.image.com" class="class1"></a>
    <a href="#" alt="name of item"><img src="http://some.image.com" class="class1"></a>
    <a href="#" alt="name of item"><img src="http://some.image.com" class="class1"></a>
    <a href="#" alt="name of item"><img src="http://some.image.com" class="class1"></a>
    <a href="#" alt="name of item"><img src="http://some.image.com" class="class1"></a>
    <br />
    <br />
    <h4><a href="#">Some more text</a></h4>
    <a href="#" alt="name of item"><img src="http://some.image.com" class="class1"></a>
    <a href="#" alt="name of item"><img src="http://some.image.com" class="class1"></a>
    <a href="#" alt="name of item"><img src="http://some.image.com" class="class1"></a>
    <a href="#" alt="name of item"><img src="http://some.image.com" class="class1"></a>
    <a href="#" alt="name of item"><img src="http://some.image.com" class="class1"></a>
    <a href="#" alt="name of item"><img src="http://some.image.com" class="class1"></a>
    <a href="#" alt="name of item"><img src="http://some.image.com" class="class1"></a>
    <br />
    <br />
    <h4><a href="#">Some additional text</a></h4>
    <a href="#" alt="name of item"><img src="http://some.image.com" class="class1"></a>
    <a href="#" alt="name of item"><img src="http://some.image.com" class="class1"></a>
    <a href="#" alt="name of item"><img src="http://some.image.com" class="class1"></a>
    <a href="#" alt="name of item"><img src="http://some.image.com" class="class1"></a>
    <a href="#" alt="name of item"><img src="http://some.image.com" class="class1"></a>
    <a href="#" alt="name of item"><img src="http://some.image.com" class="class1"></a>
    <a href="#" alt="name of item"><img src="http://some.image.com" class="class1"></a>
</div>

person akhanaton    schedule 17.04.2015    source источник


Ответы (2)


Вы можете просмотреть и разделить данные, например «Как разделить HTML-документ используете Nokogiri? ", но если вы знаете, какой будет тег, вы можете просто split это:

# html is the raw html string
html.split('<h4').map{|g| Nokogiri::HTML::DocumentFragment.parse(g).css('a') }

page = Nokogiri::HTML(html).css("#right_holder")
links = page.children.inject([]) do |link_hash, child|
  if child.name == 'h4'
    name = child.text
    link_hash << { :name => name, :content => ""}
  end

  next link_hash if link_hash.empty?
  link_hash.last[:content] << child.to_xhtml
  link_hash
end

grouped_hsh = links.inject({}) do |hsh, link|
  hsh[link[:name]] = Nokogiri::HTML::DocumentFragment.parse(link[:content]).css('a')
  hsh
end

# {"Some text"=>[#<Nokogiri::XML::Element:0x3ff4860d6c30,
#  "Some more text"=>[#<Nokogiri::XML::Element:0x3ff486096c20...,
#  "Some additional text"=>[#<Nokogiri::XML::Element:0x3ff486f2de78...}
person Ebtoulson    schedule 17.04.2015
comment
это получает все ссылки, но не разделяет их в соответствии с тегами ‹h4›, мне нужно знать, из каких тегов ‹h4› происходит каждая ссылка. Спасибо - person akhanaton; 18.04.2015
comment
ive обновил свое решение, чтобы следовать стратегии, которую я связал. В моем исходном решении в качестве первой ссылки в массиве использовались ссылки h4 a, но оно также включало любые ссылки до h4s. - person Ebtoulson; 18.04.2015

В общем, вы бы сделали:

page.search('h4 a').each do |a|
  puts a[:href]
end

Но я уверен, что вы уже заметили, что ни одна из этих ссылок никуда не ведет.

Обновление:

Чтобы сгруппировать их, как насчет математики набора узлов:

page.search('h4').each do |h4|
  puts h4.text
  (h4.search('~ a') - h4.search('~ h4 ~ a')).each do |a|
    puts a.text
  end
end

Это означает, что каждый a, который следует за h4 и не следует за другим h4

person pguardiario    schedule 17.04.2015
comment
Я думаю, что @akhanaton хочет, чтобы ссылки под каждой h4 a, а не фактической h4 a ссылкой. - person Ebtoulson; 18.04.2015
comment
@akhanton, в таком случае это: h4 ~ a - person pguardiario; 18.04.2015
comment
это получает все ссылки, но не разделяет их в соответствии с тегами ‹h4›, мне нужно знать, из каких тегов ‹h4› происходит каждая ссылка. Спасибо - person akhanaton; 18.04.2015