watir-webdriver cookie jar saving and loading

前端 未结 2 430
半阙折子戏
半阙折子戏 2021-02-10 01:39

I\'m surprised there didn\'t seem to be much discussion on this.

in Mechanize I can easily read an entire cookie jar from the browser, store it to a file, and load it in

相关标签:
2条回答
  • 2021-02-10 02:22
    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
    
    0 讨论(0)
  • 2021-02-10 02:29

    Applying pOdeje's loop to repopulate the cookie jar, here's a solution that includes storing the cookies into a file, readable in a later Ruby run. A straight File.open write and read of the array had some issues I didn't wish to work around (parsing?), but YAML object serialization already bundled in Ruby was well suited to 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
    

    Still on the lookout for a pre watir-webdriver 0.5.x method, though.

    CAVEAT

    Not thoroughly tested yet but it seems I have to first load the URL to which the cookies apply, then load in my cookie jar using the above method, and finally load that URL into $browser object a second time. This is only a minor inconvenience and time cost for my case in which I'm staying within the same domain throughout my web session, but I can see this turning into a real thorn for cookie jars affecting several unrelated sites (as had indeed been an expectation for my old programs using other languages & libraries like Mechanize). Curl and Wget and generally other tools I've used for SOAP interfacing always let me control my POST/session/cookie environments prior to site loading. Just a thought.

    0 讨论(0)
提交回复
热议问题