Skip to content

Instantly share code, notes, and snippets.

@cia-rana
Last active September 1, 2020 01:56
Show Gist options
  • Save cia-rana/43c1f76ad63467a5e2a8e0b44c7e3213 to your computer and use it in GitHub Desktop.
Save cia-rana/43c1f76ad63467a5e2a8e0b44c7e3213 to your computer and use it in GitHub Desktop.
Google Trends API
require "net/http"
require "uri"
require "json"
require "openssl"
TIMEZONE = (-9 * 60).to_s
HL = "en"
keywords = ["bitcoin"]
def get_ready(keywords)
u = URI.parse("https://trends.google.com/trends/api/explore")
u.query = URI.encode_www_form(
[
["hl", HL],
["tz", TIMEZONE],
["req", JSON.generate({"comparisonItem" => ["keyword" => keywords[0].to_s, "geo" => "", "time" => "now 7-d"], "category" => 0, "property" => ""})]
]
)
h = Net::HTTP.new(u.host, u.port)
h.use_ssl = true
h.verify_mode = OpenSSL::SSL::VERIFY_NONE
return JSON.parse(h.start{h.get(u.path + ?? + u.query)}.body[5..-1])["widgets"]
end
def get_interest_over_time(request, token)
request["requestOptions"]["category"] = 0
request["requestOptions"]["property"] = ""
u = URI.parse("https://trends.google.com/trends/api/widgetdata/multiline")
u.query = URI.encode_www_form(
[
["hl", HL],
["tz", TIMEZONE],
["req", JSON.generate(request)],
["token", token]
]
)
h = Net::HTTP.new(u.host, u.port)
h.use_ssl = true
h.verify_mode = OpenSSL::SSL::VERIFY_NONE
return JSON.parse(h.start{h.get(u.path + ?? + u.query)}.body[5..-1])
end
ready_data = get_ready(keywords)
timelineData = get_interest_over_time(ready_data[0]["request"], ready_data[0]["token"])["default"]["timelineData"]
puts timelineData.map{|e|
manth, day, year, _, time, am_pm = e["formattedTime"].split
value = e["value"][0]
"#{manth} #{day.rjust(3)} #{year} at #{time.rjust(5)} #{am_pm}:#{?X*value} #{value}"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment