【问题标题】:How do I parse HTML using Nokogiri?如何使用 Nokogiri 解析 HTML?
【发布时间】:2013-08-15 15:46:49
【问题描述】:

我想解析一个 HTML 文件,提取相关数据以用于我的研究。这是一段 HTML:

<td class="color_line1" valign="center"><a class="linkpadrao" href="javascript:Direciona('5453*SERRA@TALHADA');">Serra Talhada</a></td>
<td class="color_line" valign="center" align="center">9</td>
<td class="color_line" valign="center" align="center">2,973</td>
<td class="color_line" valign="center" align="center">0,016</td>
<td class="color_line" valign="center" align="center">2,939</td>
<td class="color_line" valign="center" align="center">3,000</td>
<td class="color_line" valign="center" align="center">0,572</td>
<td class="color_line" valign="center" align="center">2,401</td>
<td class="color_line" valign="center" align="center">0,024</td>
<td class="color_line" valign="center" align="center">2,378</td>
<td class="color_line" valign="center" align="center">2,426</td>
</tr>

更具体地说,我想获得“Serra Talhada”(作为城市名称),以及城市名称下方的所有数字(它是汽油的最高、最低和平均价格)。

到目前为止我已经试过了:

require 'rubygems'
require 'mechanize'
require 'nokogiri'
require 'open-uri'

url = "http://www.anp.gov.br/preco/prc/Resumo_Por_Estado_Municipio.asp"

agent = Mechanize.new

parameters = {'selSemana' => '737*De+28%2F07%2F2013+a+03%2F08%2F2013',
  'desc_semana' => 'de+28%2F07%2F2013+a+03%2F08%2F2013',
  'cod_Semana' => '737',
  'tipo' => '1',
  'Cod_Combustivel' => 'undefined',
  'selEstado' => 'PE*PERNAMBUCO',
  'selCombustivel' => '487*Gasolina',
}

municipio = []

page = agent.post(url, parameters)

extrair = page.parser

extrair.css('.linkpadrao').each do |posto|
    # Municipios
    municipio << posto.text 
end

我不知道如何获取这些数字,因为它们具有相同的 HTML 结构。

有什么想法吗?!

【问题讨论】:

    标签: ruby html-parsing nokogiri


    【解决方案1】:

    由于您需要找到与城市链接相关的单元,因此您应该找到它们的共同祖先 - 在本例中是它们的 tr。

    使用 xpath,您可以通过文本定位特定单元格:

    # This is the table that contains all of the city data
    data_table = extrair.at_css('.table_padrao')
    
    # This is the specific row that contains the specified city
    row = data_table.xpath('//tr[td/a[@class="linkpadrao" and text()="Serra Talhada"]]')
    
    # This is the data in the specific row
    data = row.css(".color_line").map{|e| e.text }
    #=> ["9", "2,973", "0,016", "2,939", "3,000", "0,572", "2,401", "0,024", "2,378", "2,426"]
    

    【讨论】:

    • 为什么要花一点点 css 把它变成丑陋的 xpath 表达式?
    • @pguardiario,我认为他们想要基于文本的表格中的特定行,因此需要 xpath。
    【解决方案2】:

    您可以通过以下方式获取每个帖子后面的数字:

    posto.parent.search('~ td').map &:text
    

    【讨论】:

    • +1 混合 DOM 方法和 CSS 选择器通常是最易读的解决方案。
    猜你喜欢
    • 2013-04-19
    • 2011-01-04
    • 2013-04-27
    • 2013-04-02
    • 2011-09-08
    • 2011-11-16
    • 2012-02-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多