Last active
December 14, 2015 12:58
-
-
Save sharapeco/5089792 to your computer and use it in GitHub Desktop.
石川県の大気環境の状況を取得。作りかけ。 取得元 http://www.pref.ishikawa.jp/cgi-bin/taiki/top.pl / プロジェクト継続先 https://github.com/kitak/ishikawa_air_pollution
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'rubygems' | |
require 'mechanize' | |
class IshikawaAirPollutionAPI | |
def initialize() | |
@use_sleep = false | |
@agent = Mechanize.new | |
@agent.user_agent_alias = 'Mac Safari' | |
@agent.request_headers = { | |
'Accept' => 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', | |
'Accept-language' => 'ja-jp', | |
'Accept-charset' => '', | |
'Accept-encoding' => 'gzip, deflate', | |
'Keep-alive' => nil | |
} | |
end | |
def pm25(args) | |
measure = {} | |
page = @agent.get('http://www.pref.ishikawa.jp/cgi-bin/taiki/top.pl') | |
# 測定日時を取得 | |
measure_date = nil | |
measure_time = nil | |
page.search('#subhead div').each do |div| | |
text = div.text | |
measure_date = text if /(\d{4})年(\d{2})月(\d{2})日/ =~ text | |
measure_time = text if /\d{2}:\d{2}/ =~ text | |
end | |
measure['date'] = measure_date | |
measure['time'] = measure_time | |
# データテーブルを探す | |
points = [] | |
page.search('table').each do |table| | |
next if table.search('td')[0].text != '測定局名' | |
# テーブルヘッダをキーにする | |
header = [] | |
targetKey = nil | |
trs = table.search('tr') | |
thead = trs.shift | |
thead.search('td').each do |td| | |
key = td.text | |
targetKey = key if /PM2\.5/ =~ key | |
header.push(key) | |
end | |
raise 'invalid form' if !targetKey | |
# データをなめる | |
rows = [] | |
trs.each do |tr| | |
row = {} | |
i = 0 | |
tr.search('td').each do |td| | |
row[ header[i] ] = td.text.gsub(/\302\240/, ' ').strip | |
i += 1 | |
end | |
rows.push(row) | |
points.push({ | |
'name' => row['測定局名'], | |
'value' => row[targetKey], | |
}) if row[targetKey] != '' | |
end | |
end | |
measure['points'] = points | |
measure | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment