Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Nokogiri and Selenium, is it possible to skip a command if the driver is unable to perform it?

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?

like image 788
Joe Morano Avatar asked Dec 25 '22 04:12

Joe Morano


2 Answers

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
like image 84
chipairon Avatar answered Apr 08 '23 16:04

chipairon


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

like image 38
Joe Sebin Avatar answered Apr 08 '23 18:04

Joe Sebin