Skip to content

Instantly share code, notes, and snippets.

@tlnagy tlnagy/MuniScraper.jl
Last active Aug 20, 2019

Embed
What would you like to do?
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"]
# 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))))
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, Base.Filesystem.mtime(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...")
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 minute
[Timer]
OnBootSec=5min
OnCalendar=*:0/1
[Install]
WantedBy=basic.target
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.