Skip to content

Instantly share code, notes, and snippets.

@octosteve
Created December 11, 2013 04:50
Show Gist options
  • Save octosteve/7905224 to your computer and use it in GitHub Desktop.
Save octosteve/7905224 to your computer and use it in GitHub Desktop.
Mechanize USPSification Station
# make sure you gem install mechanize
require 'mechanize'
# fake it like we're safari
a = Mechanize.new { |a| a.user_agent_alias = 'Mac Safari'}
# look up all mail boxes in 10001. This returns 50 results.
a.get('https://tools.usps.com/go/POLocatorAction!input.action?address=10001&radius=1000&locationTypeQ=collectionbox#paginationTop')
# a is now 'on' that page
# returns all of the location ids on the page
a.page.search('#locationID').map(&:text)
# This will probably be replaced by a model of Collection box
CollectionBox = Struct.new(:address, :city, :state, :zip, :location_id, :phone, :latitude, :longitude)
# Gets all 50 boxes on the page and wraps them in an object. 10 to 21 returns an array.
boxes = a.page.search('.result').map do |location|
address = location.search('.addressLn').text
city = location.search('.cityLn').text
state = location.search('.stateLn').text
zip = location.search('.zip-code').text
location_id = location.search('.location-ID').text
phone = location.search('.phoneNum').text
latitude = location.search('div.flag').attr('lat').text
longitude = location.search('div.flag').attr('lon').text
CollectionBox.new(address, city, state, zip, location_id, phone, latitude, longitude)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment