如何使用 ruby 将 table headers 和行合并到地图中?

how to combine a table headers and rows in to a map using ruby?

虽然使用页面对象 gem 我能够获得 header 和 table 的行,但我无法使用下面的代码将其转换为散列仅将第一行映射到 headers 但我需要完整的 table 行映射到 header.

这是 table 数据的 link:https://www.w3schools.com/html/html_tables.asp

我试过下面的代码:

class WbPage
  include PageObject

  page_url 'https://www.w3schools.com/html/html_tables.asp'

  table(:customers, id: 'customers')

  def get_table_data
    headers = customers_element.ths.collect { |th| th.inner_html }
    rows = customers_element.tds.collect { |td| td.inner_html }
    data = {}
    headers.zip(rows) { |header,row| data[header.to_sym] = row }
    puts data
  end

end

我得到上面代码的以下输出:

{:Company=>"Alfreds Futterkiste", :Contact=>"Maria Anders", :Country=>"Germany"}

但我需要这样:

{:Company => "Alfreds Futterkiste", "Centro comercial Moctezuma", "Ernst Handel", "Island Trading", "Laughing Bacchus Winecellars", "Giovanni Rovelli"
:Contact => "Maria Anders", "Francisco Chang", "Roland Mendel", "Helen Bennett", "Yoshi Tannamuri", "Magazzini Alimentari Riuniti"
:Contry => "Germany", "Mexico", "Austria", "UK", "Canada", "Italy"}

如果我有这样的 table 怎么办

--------------------------------------------------
 Location     |       Time     |           Miles   <-- First tr with headers (I need to ignore it)
--------------------------------------------------
Fuel | Inspection | State | Zone | ETA | ETD |     <-- Second tr with headers (from here i need the data)
--------------------------------------------------
F | I | Omaha | Nebraska | 27 08:00 | 27 08:30 | 
F | I | Omaha | Nebraska | 27 08:00 | 27 08:30 |
F | I | Omaha | Nebraska | 27 08:00 | 27 08:30 |
F | I | Omaha | Nebraska | 27 08:00 | 27 08:30 |
F | I | Omaha | Nebraska | 27 08:00 | 27 08:30 |

问题是 rows 实际上是单个数据单元格而不是数据列。当你用 headers 压缩它时,你在 size/data.

上不匹配

我认为最简单的解决方案是使用 Watir 的 Table#strings 方法将 table 数据转换为行数据数组,可以转置以获取列数据:

def get_table_data
  data = {}
  customers_element.strings.transpose.each { |col| data[col.shift.to_sym] = col }
  data
end