gpt4 book ai didi

ruby - 如何使用 ruby​​ 将表头和行组合到 map 中?

转载 作者:数据小太阳 更新时间:2023-10-29 08:42:23 26 4
gpt4 key购买 nike

虽然使用 pageobject gem 能够获取表的标题和行,但无法使用以下代码将其转换为散列,但我只能将第一行映射到标题,但我需要映射完整的表行到标题。

如何使用 nokogiri 来做到这一点,因为表很大并且需要很长时间才能加载

这是表格数据的链接: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"}

如果我有这样的表怎么办

--------------------------------------------------
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 压缩它时,大小/数据不匹配。

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

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

关于ruby - 如何使用 ruby​​ 将表头和行组合到 map 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57662276/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com