Search code examples
ruby-on-railsrubycookiesmechanizenet-http

How to get a list of website (url) cookies with Ruby


I'd like to know if there's a clean way of getting a list of cookies that website (URL) uses?

Scenario: User writes down URL of his website, and Ruby on Rails application checks for all cookies that website uses and returns them. For now, let's think that's only one URL.

I've tried with these code snippets below, but I'm only getting back one or no cookies:

url = 'http://www.google.com'
r = HTTParty.get(url)
puts r.request.options[:headers].inspect
puts r.code

or

uri = URI('https://www.google.com')
res = Net::HTTP.get_response(uri)
puts "cookies: " + res.get_fields("set-cookie").inspect
puts res.request.options[:headers]["Cookie"].inspect

or with Mechanize gem:

agent = Mechanize.new
page = agent.get("http://www.google.com")
agent.cookies.each do |cooky| puts cooky.to_s end

It doesn't have to be strict Ruby code, just something I can add to Ruby on Rails application without too much hassle.


Solution

  • You should use Selenium-webdriver:
    you'll be able to retrieve all the cookies for given website:

    require "selenium-webdriver"
    
    
    @driver = Selenium::WebDriver.for :firefox #assuming you're using firefox
    
    @driver.get("https://www.google.com/search?q=ruby+get+cookies+from+website&ie=utf-8&oe=utf-8&client=firefox-b-ab")
    
    @driver.manage.all_cookies.each do |cookie|
        puts cookie[:name]
    end