Skip to content

Instantly share code, notes, and snippets.

@eoinkelly
Created September 19, 2016 07:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eoinkelly/eb7cc5b449665fbe436a521c38b6e33b to your computer and use it in GitHub Desktop.
Save eoinkelly/eb7cc5b449665fbe436a521c38b6e33b to your computer and use it in GitHub Desktop.
Command line tool to get upcoming bus departures for a particular stop in Wellington NZ
#!/usr/bin/env ruby
require "nokogiri"
require "net/http"
courtenay_place = 5002 # Get your stop number from the metlink.co.nz website
buses_i_care_about = %w(52 56 57 58)
# .../departures returns 20 results
# .../departures?more=1 returns 40 results
# .../departures?more=2 returns 60 results
# .../departures?more=3 returns 80 results
# .../departures?more=4 returns 100 results
# etc.
#
uri = URI("https://www.metlink.org.nz/stop/#{courtenay_place}/departures?more=4") # get 100 results
response = Net::HTTP.get(uri)
document = Nokogiri::HTML(response)
html_table_rows = document.css(".rt-info-content tr")
all_buses = html_table_rows.map do |tr|
tr.css("td").map { |td| td.text.strip }
end
# Example shape of all_buses
#
# ["2", "Wgtn Station", "67 mins", ""],
# ["91", "Queensgate", "69 mins", ""],
# ["54", "Churton Park", "70 mins", ""],
# ["52", "Newlands", "70 mins", ""],
# ["3", "Karori", "79 mins", ""],
# ["1", "Wgtn Station", "8:12pm", ""],
# ["14", "Wilton", "8:18pm", ""],
# ["91", "Queensgate", "8:20pm", ""],
# ["23", "Mairangi", "8:21pm", "TSG"],
# ["43", "Khandallah", "91 mins", ""],
my_buses = all_buses.select { |bus| buses_i_care_about.include? bus[0] }
my_buses.each do |bus|
puts "#{bus[0]} leaves in #{bus[2]}"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment