Skip to content

Instantly share code, notes, and snippets.

@tlnagy
Last active January 7, 2020 02:22
Show Gist options
  • Save tlnagy/23df15db5b05278d63562d02ad65a6cc to your computer and use it in GitHub Desktop.
Save tlnagy/23df15db5b05278d63562d02ad65a6cc to your computer and use it in GitHub Desktop.
A scraper for SF Muni train data (only tested on OpenSUSE Leap 15.1, Julia 1.1.1)
"""
Copyright (c) 2019 Tamas Nagy
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
using Dates
println("Scraping at $(now())")
using HTTP
using EzXML
using DataStructures
using DataFrames
using CSV
using TimeZones
filename = joinpath(@__DIR__, "ktn_data_2019_2.csv")
trains = ["KT", "N", "S", "E", "F", "J", "M", "L"]
# See https://www.nextbus.com/xmlFeedDocs/NextBusXMLFeed.pdf for details
attrs = OrderedDict(
"polltime_pct" => DateTime,
"id" => Int,
"routeTag" => String,
"dirTag" => String,
"lat" => Float64,
"lon" => Float64,
"secsSinceReport" => Int,
"predictable" => Bool,
"heading" => Int,
"speedKmHr" => Float64,
"leadingVehicleId" => Int)
# construct a new dataframe with the types from above (+ missing)
df = DataFrame(map(x->Union{x, Missing}, values(attrs)),
Symbol.(collect(keys(attrs))))
"""
last_polltime(filename)
Given a filename, this function finds the last line and attempts to parse
the datetime when the last polling occurred.
"""
function last_polltime(filename)
open(filename) do io
seekend(io)
# the last character is the EOF and the penultimate one is a '\n'
pos = position(io)-2
last_updated = now()
while pos >= 0
seek(io, pos)
# going backwards if we find a newline then we want to read the line following it
if read(io, Char) == '\n'
try
# the datetime is the first column in the row
last_updated = parse(DateTime, split(readline(io), ",")[1])
break
catch
# keep going backward in the file
end
end
# reading moves us forward so move backwards 2 times
pos = position(io) - 2
end
last_updated
end
end
if !isfile(filename)
println("No previous data detected, creating new csv: $filename")
CSV.write(filename, df)
prev_time = round(Int, Dates.datetime2unix(now())*1000)
else
# the previous time is the last time that we changed the file
prev_time = round(Int, Dates.datetime2unix(last_polltime(filename))*1000)
println("Detected scraped data, appending...")
end
baseurl = "http://webservices.nextbus.com/service/publicXMLFeed"
responses = String[]
println("Pinging NextBus servers")
for train in trains
r = HTTP.request("GET", "$baseurl?command=vehicleLocations&a=sf-muni&r=$train&t=$prev_time")
push!(responses, String(r.body))
end
# dummy functions for parsing strings
# lets us to map the parse function to all the different types
Base.parse(::Type{T}, s::AbstractString) where {T <: String} = s
Base.parse(::Type{T}, s::Missing) where {T <: Any} = missing
Base.parse(::Type{T}, d::DateTime) where {T <: DateTime} = d
function get_key(node::EzXML.Node, k::String)
if k == "polltime_pct"
# convert from unix time -> utc datetime -> pacific time
d = Dates.unix2datetime(parse(Int, findfirst("//lastTime", node)["time"])÷1000)
zd = ZonedDateTime(d, TimeZone("US/Pacific", TimeZones.Class(:LEGACY)), from_utc=true)
return DateTime(zd)
end
try
return node[k]
catch
return missing
end
end
println("Massaging data into dataframe")
for response in responses
xml = parsexml(response)
for vehicle in findall("//vehicle", xml)
t = Tuple(parse(keytype, get_key(vehicle, key)) for (key, keytype) in attrs)
push!(df, t)
end
end
print("Saving $(size(df, 1)) lines...")
CSV.write(filename, df, append=true)
println("Done.")
# ~/.config/systemd/user/muniscraper.service
[Unit]
Description=Pings the muni servers and records the data
[Service]
ExecStart=/home/tlnagy/Documents/julia-1.1.1/bin/julia /home/tlnagy/Documents/MuniScraper.jl
[Install]
WantedBy=multi-user.target
# place in ~/.config/systemd/user/
# activate using systemctl --user enable muniscraper.timer
# and start using systemctl --user start muniscraper.timer
[Unit]
Description=Run scraper every 30 seconds
[Timer]
OnActiveSec=0
OnUnitActiveSec=30
AccuracySec=1us
OnBootSec=1min
[Install]
WantedBy=basic.target
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment