gpt4 book ai didi

ruby - 从表中的类名创建动态变量,将 td 值移动到该行数组或散列中?

转载 作者:行者123 更新时间:2023-12-04 16:22:32 24 4
gpt4 key购买 nike

我是一名业余程序员,想从与此站点类似的站点中抓取数据:http://www.highschoolsports.net/massey/ (顺便说一下,我有权抓取该网站。)

目标站点在行 [0] 中的每个 'th' 都有 'th' 类,但我想确保我从每个表中提取的每个 'TD' 都以某种方式链接到该 th 的类名,因为这些表是不一致的,例如一张 table 可能是:

row[0] ->>th.name, th.place, th.team

行[1] ->>td[0], td[1], td[2]

而另一个可能是:

row[0] ->>th.place, th.team, th.name

行[1] ->>td[0]、td[1]、td[2] 等。

我的问题:如何在数百个不一致的表中捕获“th”类名(按“th”类顺序)并创建 10-14 个变量(数组),然后链接与该列对应的“td”在表中的那个动态变量?请让我知道这是否令人困惑.. 给定页面上有多个表格..

目前我的代码是这样的:

require 'rubygems'
require 'mechanize'
require 'nokogiri'
require 'uri'

class Result

def initialize(row)
@attrs = {}
@attrs[:raw] = row.text
end

end

class Race

def initialize(page, table)
@handle = page
@table = table
@results = []
@attrs = {}
parse!
end

def parse!
@attrs[:name] = @handle.css('div.caption').text
get_rows

end

def get_rows
# get all of the rows ..
@handle.css('tr').each do |tr|
@results << RaceResult.new(tr)
end
end

end

class Event

class << self

def all(index_url)
events = []
ourl = Nokogiri::HTML(open(index_url))
ourl.css('a.event').each do |url|
abs_url = MAIN + url.attributes["href"]
events << Event.new(abs_url)
end
events
end

end

def initialize(url)
@url = url
@handle = nil
@attrs = {}
@races = []
@sub_events = []
parse!
end

def parse!
@handle = Nokogiri::HTML(open(@url))
get_page_meta
if(@handle.css('table.base.event_results').length > 0)
@handle.search('div.table_container.event_results').each do |table|
@races << Race.new(@handle, table)
end
else
@handle.css('div.centered a.obvious').each do |ol|
@sub_events << Event.new(BASE_URL + ol.attributes["href"])
end
end
end

def get_page_meta
@attrs[:name] = @handle.css('html body div.content h2 text()')[0] # event name
@attrs[:date] = @handle.xpath("html/body/div/div/text()[2]").text.strip #date
end

end

一个 friend 一直在帮助我解决这个问题,我刚刚开始掌握 OOP,但我只是捕获表,它们没有分成 td 并存储到某种变量/数组/哈希等中。我需要帮助理解这个过程或如何做到这一点。关键部分是根据数据的类别动态分配变量名称,并将“td”从该列(例如所有 td[2])移动到该动态变量名称中。我无法告诉你,如果有人真的可以帮助我解决这个问题并了解如何完成这项工作,那该有多好。预先感谢您的任何帮助!

最佳答案

一旦您意识到 th 内容是您的散列的键,这很容易。例子:

@items = []
doc.css('table.masseyStyleTable').each do |table|
fields = table.css('th').map{|x| x.text.strip}
table.css('tr').each do |tr|
item = {}
fields.each_with_index do |field,i|
item[field] = tr.css('td')[i].text.strip rescue ''
end
@items << item
end
end

关于ruby - 从表中的类名创建动态变量,将 td 值移动到该行数组或散列中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7870608/

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