Skip to content

Instantly share code, notes, and snippets.

@huezoaa
Created January 30, 2015 20:37
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 huezoaa/712894eb416c4de70aea to your computer and use it in GitHub Desktop.
Save huezoaa/712894eb416c4de70aea to your computer and use it in GitHub Desktop.
Stock Ticket Bonus
require 'HTTParty'
require 'json'
require 'nokogiri'
### Obtain stock symbol:
puts "Please enter your Stock Symbol:"
stock_symbol = gets.chomp
address = "http://finance.yahoo.com/q?s=" + stock_symbol
# puts address
### run a GET from Yahoo with HTTParty for your stock symbol, assign to response
response = HTTParty.get("#{address}")
### take response body and use Nokogiri to parse the HTML into a Ruby variable
ticker = Nokogiri::HTML(response.body)
span = "//span[@id='yfs_l84_" + stock_symbol.downcase + "\']"
# puts span
### use the xpath method to isolate the stock value from the parsed HTML
### use the .first method to get the first element of the NodeSet
#puts ticker.xpath("//span[@id='yfs_l84_aapl']").first
### The output of the above "contains" my desired value.
### Use the .content method to get the value only:
# puts ticker.xpath("#{span}").first.content
value = ticker.xpath("#{span}").first.content
# p ticker
puts stock_symbol + "\'s Stock value is: $#{value}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment