Vishal G
Vishal G

Reputation: 1541

How to save and load cookies using Ruby + Selenium WebDriver

How can I save all cookies in Ruby's Selenium WebDriver to a txt-file, then load them later? I don't find any answer which does export and import at the same time

In python looks like a very easy way to do that, how to do it in RUBY?

How to save and load cookies using Python + Selenium WebDriver:

import pickle
import selenium.webdriver 

driver = selenium.webdriver.Firefox()
driver.get("http://www.google.com")
pickle.dump( driver.get_cookies() , open("cookies.pkl","wb"))

Edits: I am only using Selenium WebDriver (no capybara etc)

Upvotes: 1

Views: 2212

Answers (1)

Vasfed
Vasfed

Reputation: 18504

In tests you can use gem show_me_the_cookies (a wrapper/adapter)

cookies = show_me_the_cookies # => [{:name, :domain, :value, :expires, :path, :secure}]
# here you can write them as you like
# and then load and
cookies.each{|c|
  create_cookie(c[:name], c[:value], path: c[:path], domain: c[:domain]) # etc.
}

Without gems you can call directly to selenium driver:

driver = Capybara.current_session.driver # or get your selenium driver other way if not using capybara
cookies = driver.browser.manage.all_cookies
# be sure that you've visited a page in your app, selenium cannot create cookies at `about:blank`
driver.browser.manage.add_cookie(name: ..., value:...)

Upvotes: 2

Related Questions