I'm trying to automate an action on my website. Every so often, I want a bot to visit certain pages and click an element. Sometimes, this element isn't there, and that breaks the whole thing because the bot doesn't know what to do. Ideally, I'd like to record how many times the element isn't there, but at minimum I'd like the bot to skip that page and keep going.
Here's what I have so far:
require "selenium-webdriver"
require "nokogiri"
driver = Selenium::WebDriver.for :chrome
wait = Selenium::WebDriver::Wait.new(:timeout => 19)
User.all.each do |u|
driver.navigate.to "http://website.com/" + u.name
driver.find_element(:class, "like").click #THIS IS THE LINE THAT SOMETIMES FAILS
end
browser.close
So ideally, in place of just driver.find_element(:class, "like").click
, I'd like something like:
if element(:class, "like").exists?
driver.find_element(:class, "like").click
else
u.error = true
u.save
end
Is that possible?
Following @max pleaner advice, you could rescue the exception about not finding the element and then do something with that information. The exception you are looking for in this case is NoSuchElementError.
The code could look like this:
User.all.each do |u|
driver.navigate.to "http://website.com/" + u.name
begin
driver.find_element(:class, "like").click #THIS IS THE LINE THAT SOMETIMES FAILS
rescue Selenium::WebDriver::Error::NoSuchElementError
u.error = true
u.save
end
end
yes.its possible.try the following code
User.all.each do |u|
driver.navigate.to "http://website.com/" + u.name
if driver.find_elements(:class, "like").count > 1
driver.find_element(:class, "like").click
end
end
you can also ensure the continuity through exception handling in ruby like begin rescue ensure
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With