Search code examples
rubywhile-loopwatir-webdriverwebautomation

How can I get my script to loop?


I have it where my script signs in and goes to a browser url, yet when it signs out of the current web page it just sits there and won't restart the loop. How can I get the loop to realize its done and to restart?

x = 0

while x <= 5

File.open("yahoo_accounts.txt") do |email|
    email.each do |item|
    email, password = item.chomp.split(',')
    emails << email 
    passwords << password
    emails.zip(passwords) { |name, pass| 
        browser = Watir::Browser.new :ff
        browser.goto "url"

    #logs in and does what its suppose to do with the name and pass

        }
    end
    x += 1
    next
end
end

When the script is done it just sits at the webpage...I'm trying to get it to go to the beginning again... You would think it would take each name,pass and go back to the beginning url. Thanks for your help.


Solution

  • It looks like you may not be calling browser.close appropriately. In my quick mock-up testing, I definitely get weird behaviour if I don't do that. You're also using non-idiomatic Ruby looping. Try this:

    5.times do 
      File.open("yahoo_accounts.txt") do |email|
        email.each do |item|
          email, password = item.chomp.split(',')
          emails << email 
          passwords << password
          emails.zip(passwords) do |name, pass| 
            browser = Watir::Browser.new :ff
            browser.goto "url"
    
            #logs in and does what its suppose to do with the name and pass
    
            browser.close
          end
        end
      end
    end
    

    EDIT:

    Alternatively, if you want the same exact Watir::Browser instance to be doing all the work, initialize and close outside of your main loop. Right now, you're spawning a new Browser instance with every iteration of emails.zip, times every iteration of email.each, times the 5 iterations of your while loop. This is just ungainly, and may be screwing up your expected results. So just doing:

    browser = Watir::Browser.new :ff
    5.times do
      ... loop code ...
    end
    browser.close
    

    Will at least make whatever's happening under the hood clearer.