通过 class 和 Mechanize/Nokogiri 在最近的前一个兄弟中获取文本值
Getting text value in closest preceding sibling by class with Mechanize/Nokogiri
目前我正在遍历 table 行并从 td 获取值,将它们放入由兄弟 td 中的值标识的排序哈希中:
Ruby 片段
@counts = Hash.new
agent.page.search('.child').each do |child|
@counts[child.css('td')[0].text.strip!] = child.css('td')[1].text.gsub(/,/,'').to_i
end
puts @counts.sort_by{|k,v| v}.reverse.to_h
HTML结构
<tr class="parent">
<td class="info">Type</td>
<td>12,000</td>
</tr>
<tr class="child">
<td class="info">Sub Type</td>
<td>9,000</td>
</tr>
<tr class="child">
<td class="info">Sub Type</td>
<td>3,000</td>
</tr>
<tr class="parent">
<td class="info">Type</td>
<td>11,000</td>
</tr>
<tr class="child">
<td class="info">Sub Type</td>
<td>11,000</td>
</tr>
现在我想更改散列键,方法是将它们与属于父 tr 的 td 中的文本值连接起来。所以在上面的 HTML 结构中,而不是 "Sub Type" => 9000,"Sub Type" => 3000 等。我想得到 "Type Sub Type" => 9000,"Type Sub Type" => 3000 等
当兄弟姐妹的数量未知时,如何获得具有特定 class 的第一个兄弟姐妹?
您可以换一种方式看待这个问题,遍历所有 tr
元素(父元素和子元素),保留最后找到的父类型,然后在找到子元素时连接最后一个父类型。
@counts = Hash.new
parent = nil
agent.page.search('.parent, .child').each do |node|
type = node.css('td')[0].text.strip
value = node.css('td')[1].text.gsub(/,/, '').to_i
if node['class'].include? 'parent'
parent = type
else
@counts["#{parent} #{type}"] = value
end
end
puts @counts.sort_by{|k,v| v}.reverse.to_h
此外,哈希本质上是一种未排序的数据结构。如果您想保留顺序,那么最好的选择是元组数组。换句话说,[['Type Sub Type', 12000], ['Type Sub Type', 11000], ..., ['Type Sub Type', 3000]]
。只需删除最后一行末尾的 .t_h
即可获得那种结果。
目前我正在遍历 table 行并从 td 获取值,将它们放入由兄弟 td 中的值标识的排序哈希中:
Ruby 片段
@counts = Hash.new
agent.page.search('.child').each do |child|
@counts[child.css('td')[0].text.strip!] = child.css('td')[1].text.gsub(/,/,'').to_i
end
puts @counts.sort_by{|k,v| v}.reverse.to_h
HTML结构
<tr class="parent">
<td class="info">Type</td>
<td>12,000</td>
</tr>
<tr class="child">
<td class="info">Sub Type</td>
<td>9,000</td>
</tr>
<tr class="child">
<td class="info">Sub Type</td>
<td>3,000</td>
</tr>
<tr class="parent">
<td class="info">Type</td>
<td>11,000</td>
</tr>
<tr class="child">
<td class="info">Sub Type</td>
<td>11,000</td>
</tr>
现在我想更改散列键,方法是将它们与属于父 tr 的 td 中的文本值连接起来。所以在上面的 HTML 结构中,而不是 "Sub Type" => 9000,"Sub Type" => 3000 等。我想得到 "Type Sub Type" => 9000,"Type Sub Type" => 3000 等
当兄弟姐妹的数量未知时,如何获得具有特定 class 的第一个兄弟姐妹?
您可以换一种方式看待这个问题,遍历所有 tr
元素(父元素和子元素),保留最后找到的父类型,然后在找到子元素时连接最后一个父类型。
@counts = Hash.new
parent = nil
agent.page.search('.parent, .child').each do |node|
type = node.css('td')[0].text.strip
value = node.css('td')[1].text.gsub(/,/, '').to_i
if node['class'].include? 'parent'
parent = type
else
@counts["#{parent} #{type}"] = value
end
end
puts @counts.sort_by{|k,v| v}.reverse.to_h
此外,哈希本质上是一种未排序的数据结构。如果您想保留顺序,那么最好的选择是元组数组。换句话说,[['Type Sub Type', 12000], ['Type Sub Type', 11000], ..., ['Type Sub Type', 3000]]
。只需删除最后一行末尾的 .t_h
即可获得那种结果。