Saving and loading the watir-webdriver cookie drive

I am surprised that there did not seem to be much discussion of this.

in Mechanize I can easily read the entire cookie jar from the browser, save it to a file and upload it to a later session / launch before loading the pages of the website again.

How can I do the same with watir-webdriver ?

UPDATE

Now 0.5.2 I see new methods browser.cookies.to_hash which would turn this question into "How to implement .from_hash or a similar loader using, for example, .clear and .add ?"

However, I would be particularly interested in downloading and storing all cookies using previous versions (0.4.1), which are likely to linger on my servers for some time. Perhaps through the driver Selena?

+4
source share
2 answers
 browser = Watir::Browser.new :firefox browser.goto 'http://google.com' # save cookies saved_cookies = browser.cookies.to_a # clear and get new cookies browser.cookies.clear browser.goto 'http://google.com' # set new cookies browser.cookies.clear saved_cookies.each do |saved_cookie| browser.cookies.add(saved_cookie[:name], saved_cookie[:value]) end 
+7
source

Using the pOdeje loop to refill the cookie doll, here is a solution that involves saving cookies to a file, which can be read the next time you run Ruby. Direct File.open writing and reading the array had some problems that I didn’t want to work with (parsing?), But Serializing YAML objects already associated with Ruby was well suited for the task.

 require 'yaml' # Save/serialize cookies # File.open("ST.cookies.txt", 'w').write $browser.cookies.to_a.to_s File.open("ST.cookies.yaml", 'w').write YAML::dump($browser.cookies.to_a) # Load/deserialize cookies # $cookies = File.open("ST.cookies.txt", 'r').to_a # returns 1-elem array of single long line, not indiv elements $cookies = YAML::load(File.open("ST.cookies.yaml", 'r')) $browser.cookies.clear $cookies.each do |saved_cookie| $browser.cookies.add saved_cookie[:name], saved_cookie[:value], :domain => saved_cookie[:domain], :expires => saved_cookie[:expires], :path => saved_cookie[:path], :secure => saved_cookie[:secure] end 

However, when searching for the pre watir-webdriver 0.5.x .

CAVEAT

Not fully verified, but it seems to me that I must first download the URL to which cookies are applied, and then load in the cookie jar using the above method, and finally load this URL into the $browser object a second time . These are just minor inconveniences and time costs for my case when I stay in the same domain throughout my web session, but I see that this turns into a real thorn for cookie banners affecting several unrelated sites (as it was in fact the expectation my old programs using other languages ​​and libraries like Mechanize). Curl and Wget, and in general other tools that I used for SOAP interaction, always allow me to control the POST / session / cookie environment before the site loads. Just a thought.

+4
source

Source: https://habr.com/ru/post/1395902/


All Articles