如何使用ruby将表头和行合并到地图中? [英] how to combine a table headers and rows in to a map using ruby?
问题描述
虽然使用pageobject gem可以获取表的标头和行,但是无法使用下面的代码将其转换为哈希,但是只能将第一行映射到标头,但是我需要映射完整的表行到标题.
While using the pageobject gem am able to get the a headers and rows of a table but am unable to convert it into a hash using the below code am able to get only first row mapped to headers but I need complete table rows mapped to the header.
这是表格数据的链接: https://www.w3schools.com/html/html_tables.asp
Here is the link for the table data: 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
am获得上述代码的以下输出:
am getting the below output for the above code:
{: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"}
如果我有这样的桌子怎么办
What if I have the table like this
--------------------------------------------------
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
压缩时,大小/数据不匹配.
The problem is that rows
is actually the individual data cells rather than the column of data. When you zip it with the headers
, you have a mismatch on the size/data.
我认为,简化列表的解决方案是使用Watir的Table#strings
方法将表数据转换为行数据数组,可以将其转换为行数据以获取列数据:
I think the simplist solution is to use Watir's Table#strings
method to convert the table data to an Array of row data, which can be transposed to get the column data:
def get_table_data
data = {}
customers_element.strings.transpose.each { |col| data[col.shift.to_sym] = col }
data
end
这篇关于如何使用ruby将表头和行合并到地图中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!