Sunday, March 13, 2016

How to get a Selenium/Ruby bot to wait before performing an action?

Leave a Comment

I'm building a Selenium/Ruby web bot that clicks on elements. The problem is, sometimes there isn't enough time for the page to load before the bot decides it can't find the element.

What's the Ruby way to get Selenium to wait before performing an action? I would prefer explicit waiting, but I'm fine with implicit waiting too.


I tried to use the wait.until method:

require "selenium-webdriver" require "nokogiri" driver = Selenium::WebDriver.for :chrome wait = Selenium::WebDriver::Wait.new(:timeout => 15) driver.navigate.to "http://google.com" driver.wait.until.find_element(:class, "gb_P").click 

But I'm getting the following error:

Undefined method 'wait' for <Selenium::WebDriver> 

I also tried:

require "watir-webdriver/wait" ... driver.find_element(:class, "gb_P").wait_until.click 

but that's also giving me an undefined method error:

undefined method `when_present' for #<Selenium::WebDriver...> 

3 Answers

Answers 1

You are using wait as WebDriver function, but it isn't. Try this

element = wait.until { driver.find_element(:class => "gb_P") } element.click 

Answers 2

Have you tried the when present, to wait for the button (You could also make it wait for a certain div to )

require "watir-webdriver/wait" driver.button(:class => 'gb_P').when_present.click 

As for implicit waiting

sleep *seconds* 

or a better way as to not waste time

sleep *seconds* until driver.element(:id/class/etc, 'value').exists? 

Answers 3

A potential answer is in your stacktrace.

driver.element(:class, "gb_P").when_present.click 
If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment