Last active
August 1, 2017 18:54
-
-
Save robhanlon22/b195a9fa25f1f012dc2f2ab89eb9da4f to your computer and use it in GitHub Desktop.
king county election results scraper
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
this just scrapes KING5's election "Hot Races" results page forever every 60 | |
seconds. do the whole bundle install dance then run ruby election_results.rb. if | |
you only care about Tacoma races or something, just specify that as an argument, | |
e.g. ruby election_results.rb Tacoma |
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
# frozen_string_literal: true | |
require 'bundler/setup' | |
require 'httparty' | |
require 'nokogiri' | |
def info(string) | |
"\e[93m#{string}\e[0m" | |
end | |
places = ARGV.empty? ? ['Seattle', 'King County'] : ARGV | |
loop do | |
system('clear') | |
raw = HTTParty.get('http://elections.tegna-media.com/election/results/king') | |
doc = Nokogiri::HTML(raw) | |
items = doc.css('.racelist .race_container').map do |race| | |
name = race.at_css('h2').text | |
next unless places.any? { |p| name.downcase.include?(p.downcase) } | |
results = race.css('.candidate_cont').map do |candidate| | |
%w[candidate_name candidate_votes].map do |c| | |
candidate.at_css(".#{c}").text.gsub(/\s+/, ' ').strip | |
end | |
end.to_h | |
[name, results] | |
end.compact.to_h | |
longest = items.values.flat_map(&:keys).map(&:length).max | |
items.each do |name, candidates| | |
puts info(name) | |
candidates.each do |person, votes| | |
print person.ljust(longest), ' ', votes, "\n" | |
end | |
puts | |
end | |
sleep 60 | |
end |
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
source 'https://rubygems.org' | |
ruby '2.4.1' | |
gem 'httparty' | |
gem 'nokogiri' |
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
GEM | |
remote: https://rubygems.org/ | |
specs: | |
httparty (0.15.6) | |
multi_xml (>= 0.5.2) | |
mini_portile2 (2.2.0) | |
multi_xml (0.6.0) | |
nokogiri (1.8.0) | |
mini_portile2 (~> 2.2.0) | |
PLATFORMS | |
ruby | |
DEPENDENCIES | |
httparty | |
nokogiri | |
RUBY VERSION | |
ruby 2.4.1p111 | |
BUNDLED WITH | |
1.15.3 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment