0
0

More than 1 year has passed since last update.

TOTO くじ を題材として Ruby で スクレイピング

Last updated at Posted at 2022-04-04

はじめに

Nokogiroの練習として、TOTOくじを題材にスクレイピングをやってみました。

TOTOくじ

例えば、投票状況から皆さんが本命視している組合せを調べます。

Nokogiri

require 'nokogiri'

requireします。

doc = Nokogiri::HTML.parse(html)

htmlソースをパースします。
今回は、細かなオプションなしでうまくいきました。

<tr>
<td class="zero_bar" height="26%"><img src="https://s.yimg.jp/images/toto/totoBIG/result/toto_vote_blank.gif" width="16" height="100%" title="26.56%"></td>
</tr>

// 必要な部分を抜き出す ↓

<td class="zero_bar"><img title="26.56%"></td>

スクレイピングしたい部分をまとめますと、タグにcssが対応、属性にattributeが対応していることが分かります。

doc.css('td.zero_bar img').each_with_index do |td, i|
  votes[i][0] = td.attribute('title').value.to_f
end

td.attribute('title').value"26.56%"の様な文字列ですが、to_fで変換しますと、先頭から数値に変換可能な文字のみを変換しますので、が取れます。

ソース

ruby
require 'nokogiri'
require 'open-uri'

url = 'https://toto.yahoo.co.jp/vote/toto'
html = URI.open(url){ |f| f.read }
doc = Nokogiri::HTML.parse(html)

votes = Hash.new{ |h, k| h[k] = {} }
    
doc.css('td.td_team').each_with_index do |td, i|
  votes[i + 1]["team_name"] = td.text
end
doc.css('td.zero_bar img').each_with_index do |td, i|
  votes[i][0] = td.attribute('title').value.to_f
end
doc.css('td.one_bar img').each_with_index do |td, i|
  votes[i][1] = td.attribute('title').value.to_f
end
doc.css('td.two_bar img').each_with_index do |td, i|
  votes[i][2] = td.attribute('title').value.to_f
end
doc.css('td.three_bar img').each_with_index do |td, i|
  votes[i][3] = td.attribute('title').value.to_f
end

pp votes

puts votes.values.map{ _1.key([_1[0], _1[1], _1[2], _1[3]].max) }.join(" ")
output
{1=>{"team_name"=>"京都", 0=>23.17, 1=>40.91, 2=>24.89, 3=>11.03},
 2=>{"team_name"=>"G大阪", 0=>16.93, 1=>35.15, 2=>31.69, 3=>16.23},
 3=>{"team_name"=>"磐田", 0=>43.77, 1=>39.79, 2=>11.93, 3=>4.51},
 4=>{"team_name"=>"川崎", 0=>9.35, 1=>22.94, 2=>35.91, 3=>31.8},
 5=>{"team_name"=>"広島", 0=>35.35, 1=>41.86, 2=>16.45, 3=>6.34},
 6=>{"team_name"=>"横浜M", 0=>13.53, 1=>29.19, 2=>34.92, 3=>22.36}}
1 1 0 2 1 2

第1293回 totoGOAL3の最終の人気の組合せは、1 1 0 2 1 2の様です。

まとめ

  • Nokogiri に詳しくなった
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0