Pregunta

He instalado Ruby y Mechanize. Me parece que es Posible en Nokogiri para hacer lo que quiero hacer, pero no sé cómo hacerlo.

¿Qué hay de este table? Es sólo una parte del HTML de un sitio del foro vBulletin. Traté de mantener la estructura HTML, pero eliminar algunos de los atributos de texto y etiquetas. Quiero conseguir algunos detalles por hilo como:. Título, autor, fecha, hora, respuestas, y vistas

Tenga en cuenta que hay pocas mesas en el documento HTML? Estoy después de una tabla en particular con su tbody, <tbody id="threadbits_forum_251">. El nombre será siempre el mismo (espero). ¿Puedo usar el tbody y la name en el código?

<table >
  <tbody>
    <tr>  <!-- table header --> </tr>
  </tbody>
  <!-- show threads -->
  <tbody id="threadbits_forum_251">
    <tr>
      <td></td>
      <td></td>
      <td>
        <div>
          <a href="showthread.php?t=230708" >Vb4 Gold Released</a>
        </div>
        <div>
          <span><a>Paul M</a></span>
        </div>
      </td>
      <td>
          06 Jan 2010 <span class="time">23:35</span><br />
          by <a href="member.php?find=lastposter&amp;t=230708">shane943</a> 
        </div>
      </td>
      <td><a href="#">24</a></td>
      <td>1,320</td>
    </tr>

  </tbody>
</table>
¿Fue útil?

Solución

#!/usr/bin/ruby1.8

require 'nokogiri'
require 'pp'

html = <<-EOS
  (The HTML from the question goes here)
EOS

doc = Nokogiri::HTML(html)
rows = doc.xpath('//table/tbody[@id="threadbits_forum_251"]/tr')
details = rows.collect do |row|
  detail = {}
  [
    [:title, 'td[3]/div[1]/a/text()'],
    [:name, 'td[3]/div[2]/span/a/text()'],
    [:date, 'td[4]/text()'],
    [:time, 'td[4]/span/text()'],
    [:number, 'td[5]/a/text()'],
    [:views, 'td[6]/text()'],
  ].each do |name, xpath|
    detail[name] = row.at_xpath(xpath).to_s.strip
  end
  detail
end
pp details

# => [{:time=>"23:35",
# =>   :title=>"Vb4 Gold Released",
# =>   :number=>"24",
# =>   :date=>"06 Jan 2010",
# =>   :views=>"1,320",
# =>   :name=>"Paul M"}]
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top