代码之家  ›  专栏  ›  技术社区  ›  Ramy

如何获取这组TR标签?

  •  0
  • Ramy  · 技术社区  · 13 年前

    这是实际HTML的链接:

    doc = Nokogiri::HTML(open('https://www.google.com/finance?q=NYSE%3AAA&fstype=iii'))
    

    以及一个大致的HTML片段:

    <div id="incannualdiv">
      <table id="fs-table">
        <tbody>
          <tr>..</tr>
          ...
          <tr>
            <td>Net Income</td>
            <td>100</td>
          </tr>
          <tr>..</tr>
        </tbody>
      </table>
    </div>
    

    以下是我正在处理的细节:

    doc = Nokogiri::HTML(open('https://www.google.com/finance?q=NYSE%3AAA&fstype=iii'))
    div = doc.at "div[@id='incannualdiv']" #div containing the table i want
    table = div.at 'table' #table containing tbody i want
    tbody = table.at 'tbody' #tbody containing tr's I want
    trs = tbody.at 'tr' #SHOULD be all tr's of that table/tbody - but it's only the first TR?
    

    我希望最后一点能给我所有 <TR> 标签,其中将包括 <TD> 我在找,但事实上它只给了我第一个 <TR> .

    这是下一篇:

    irb(main):023:0> a = nil
    => nil
    irb(main):024:0> doc.css('#incannualdiv > #fs-table tr').each { |e| if e.text.include? "Net Income\n"; a = e.text; end}
    => 0
    irb(main):025:0> a
    => "Net Income\n\n191.00\n611.00\n254.00\n-1,151.00\n"
    irb(main):026:0> a.split"\n"
    => ["Net Income", "", "191.00", "611.00", "254.00", "-1,151.00"]
    
    1 回复  |  直到 13 年前
        1
  •  2
  •   mraaroncruz Stephen    13 年前

    这应该可以做到。

    doc.css('#incannualdiv > #fs-table tr')
    

    at_css (我想 at )返回一个元素,其中 css 返回所有匹配项。

    编辑 :对OP意见的答复

    你可以在 tr 实际上是其子代中的文本 td s通过使用 text 方法

    trs = doc.css('#incannualdiv > #fs-table tr')
    # Get column labels from table headers
    labels = trs.first.css('th')[1..-1].map(&:text)
    net_income_tr = trs.detect { |tr|
      tr.css('td').any? { |td| td.text.strip =~ /^Net Income$/ }
    }
    # drop first tr that just has Net Income text
    # I gave up on error checking. Exercise left to reader ;)
    # this will give you an array of floats for your Net Income columns
    net_income_columns = net_income_tr.css('td')[1..-1].map { |td| td.text.gsub(',','_').to_f }
    
    labeled_values = net_income_columns.each_with_index.map { |value, i| { label: labels[i].strip, value: value } }
    
    推荐文章