作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我是一名业余程序员,想从与此站点类似的站点中抓取数据: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
最佳答案
一旦您意识到 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/
我是一名优秀的程序员,十分优秀!