Last active
December 20, 2015 05:45
-
-
Save komasaru/75bd0abfbe95814c50bb to your computer and use it in GitHub Desktop.
Ruby script to get a airport list from Flightradar24.
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
#! /usr/local/bin/ruby | |
# coding: utf-8 | |
#--------------------------------------------------------------------------------- | |
#= Flightradar24 空港情報取得 | |
# | |
# date name version | |
# 2015.12.20 mk-mode.com 1.00 新規作成 | |
# | |
# Copyright(C) 2015 mk-mode.com All Rights Reserved. | |
#--------------------------------------------------------------------------------- | |
#++ | |
require 'json' | |
require 'open-uri' | |
require 'timeout' | |
class Fr24Airports | |
URL = "http://www.flightradar24.com/_json/airports.php" # 接続先 URL | |
TIMEOUT = 10 # OpenURI 接続時のタイムアウト | |
USER_AGENT = "xxxxxxx Bot (by Ruby/#{RUBY_VERSION}, Administrator: xxxxxxxx@yyyyyyyy.zzz)" | |
# OpenURI 接続時の User-Agent, Mail Address | |
FILE_PATH = "./data/airports" # 保存ファイル | |
def exec | |
get_json # JSON 取得 | |
save_file # ファイル保存 (見やすく整形したものがよければこちら) | |
#save_file_csv # ファイル保存(CSV 形式がよければこちら) | |
rescue => e | |
$stderr.puts "[#{e.class}] #{e.message}" | |
e.backtrace.each { |tr| $stderr.puts "\t#{tr}" } | |
exit 1 | |
end | |
private | |
# JSON 取得 | |
def get_json | |
str = nil | |
timeout(TIMEOUT) do | |
str = open(URL, {"User-Agent" => USER_AGENT}) { |f| f.read } | |
end | |
@json = JSON.parse(str)["rows"].sort_by { |j| [j["country"], j["iata"]] } | |
rescue => e | |
raise | |
end | |
# ファイル保存 | |
# * 最大文字数(country: 32, name: 63) | |
# * name の末尾に改行コードが含まれていることがあるので chomp している | |
def save_file | |
File.open("#{FILE_PATH}.txt", "w") do |f| | |
str = "COUNTRY" + " " * 27 + "IATA ICAO NAME" + " " * 68 | |
str << "LAT LON ALT" | |
f.puts str | |
@json.each do |j| | |
str = sprintf("%-32s %3s %4s", j["country"], j["iata"], j["icao"]) | |
str << sprintf(" %-63s", j["name"].chomp) | |
str << sprintf(" %10.6f", j["lat"].to_f) | |
str << sprintf(" %11.6f", j["lon"].to_f) | |
str << sprintf(" %5d", j["alt"].to_i) | |
f.puts str | |
end | |
end | |
rescue => e | |
raise | |
end | |
# ファイル保存(CSV 形式) | |
# * 最大文字数(country: 32, name: 63) | |
# * name の末尾に改行コードが含まれていることがあるので chomp している | |
# * カンマが含まれる可能性のある country, name のみ "" でくくっている | |
def save_file_csv | |
File.open("#{FILE_PATH}.csv", "w") do |f| | |
f.puts "COUNTRY,IATA,ICAO,NAME,LAT,LON,ALT" | |
@json.each do |j| | |
str = "\"#{j["country"]}\",#{j["iata"]},#{j["icao"]},\"#{j["name"].chomp}\"," | |
str << "#{j["lat"]},#{j["lon"]},#{j["alt"]}" | |
f.puts str | |
end | |
end | |
rescue => e | |
raise | |
end | |
end | |
Fr24Airports.new.exec |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment