0

我有这样的代码:

until @driver.find_element(:id, "ctl00_cp_lblC").displayed?
  puts "invalid page solution"
  enter_page
end

我需要做一些方法,直到页面将有一些具有某些 id 的元素,现在它抛出错误,即 selenium 无法找到具有此 id 的元素。我做错了什么,如何解决?

也可能与 wattir 一起更容易?

4

2 回答 2

0

如 RobbieWareham 所述,如果元素不存在, find_element 将引发异常。你想要:

  1. 抢救未找到元素的异常并调用您的 enter_page 方法
  2. 将所有这些包裹在一个wait.until中,这样它就不会无限期地运行

这看起来像:

wait = Selenium::WebDriver::Wait.new(:timeout => 5) # seconds
begin
  element = wait.until do
    begin
      @driver.find_element(:id, "ctl00_cp_lblC")
    rescue
      enter_page
    end
  end
ensure
  @driver.quit
end

在Watir,这会更容易。它只是:

browser.element(:id => "ctl00_cp_lblC").wait_until_present

或者如果你需要在元素不存在时做一些事情:

browser.wait_until(2) do
  present = browser.element(:id => "ctl00_cp_lblC").present?
  enter_page unless present 
  present
end
于 2013-09-06T14:34:22.113 回答
0

Webdriver throws an error when an element is not found. Displayed? only shows whether an object is hidden or not. As you have seen, when the object is not even in the html, a NoSuchElementFound exception occurs.

Apologies for the java but you should get the idea;

Boolean elementFound = false;

    do {
        getDriver().manage().timeouts().implicitlyWait(500, TimeUnit.MILLISECONDS);
        try {
             elementFound = getDriver().findElement(By.id("ct100_cp_lblC")).isDisplayed();

        }
        catch (NoSuchElementException e){
        }   
        getDriver().navigate().refresh();  

    } while (!elementFound);

    getDriver().manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);

You would need extra code to stop an infinite loop but you shoudl get the idea.

This is a big difference between the Watir & WebDriver APIs, but I suppose it is whatever you are used to.

于 2013-09-06T14:28:32.560 回答