2013-01-07 34 views
2

我知道方法Element#wait_until_present(t),但是如果此方法超时,则会抛出timeOut异常。等待元素如果超时,不会抛出异常

有没有一种方法只需等待t秒,然后在元素出现时返回true,否则返回false?

我知道这可以用简单的begin..rescue..end声明来完成,但我正在寻找一些不使用异常的东西。

+1

没有。这种方法提出了一个例外,这种非特异性的东西肯定是不幸的,但只要写下自己的扩展名并完成它即可。 – tokland

回答

4

你可以写一个短手rescue条款是这样的:

element_present = browser.element.wait_until_present rescue false 
puts "element not present" unless element_present 

但这不过导致在全部false值上的任何Exception并不仅仅是TimeoutError。我仍然喜欢使用它,因为如果有任何Exception,那么假定该元素不存在会更安全。

1

如果你不想例外下面的代码就可以得心应手:

睡眠“你的时间在这里”如:睡眠20 - 这将等待20秒。

然后检查您的元素现在:

'your element'.exists? - 这将返回真/假

你不会以这种方式得到例外。

另一个最好的方法是根据您的需要编写您的wait_for_load方法。

+0

无论如何,'睡眠t'选项会迫使我无论睡眠时间为't'秒。我更愿意写我自己的方法,就像我在答复中所做的那样,我只是在几秒后发布:) – MichaelR

3

貌似没有其他的方法,会做什么我要找的,

所以这里是实现这一目标的最简单的方法:

#check method for Element#wait_until_present(t) 
def check_if_present(element,t) 
    raise ArgumentError, 't must be a number ' unless t.is_a? Numeric 
    begin 
     element.wait_until_present(t) 
     true 
    rescue Watir::Wait::TimeoutError 
     false 
    rescue 
     raise "Something wrong with the element" 
    end 
end