每次Selenium函数调用后休眠

时间:2014-07-21 17:50:20

标签: python selenium python-3.x

我想在执行selenium调用后等待几秒钟,以便执行自动测试的用户可以看到屏幕上发生了什么。

我的问题是:在每次函数调用之后,有没有办法等待一些秒(使用隐式或显式等待或其他),这比在代码中多次编写time.sleep更好? selenium函数调用如下所示:

driver.find_element_by_name("Account").click()

1 个答案:

答案 0 :(得分:2)

一个选项是将每个selenium调用放入自己的函数中,并使用装饰器:

def wait(secs)
    def decorator(func):
        def wrapper(*args, **kwargs):
            ret = func(*args, **kwargs)
            time.sleep(secs)
            return ret
        return wrapper
    return decorator

用法:

@wait(5) # waits 5 seconds after running the method
def do_instruction1(...):
    return "hi"

@wait(3) # waits 3 seconds after running the method
def do_instruction2(...):
    return "there"

a = do_instruction1()
print a
b = do_instruction2()
print b

输出:

<5 second delay>
"hi"
<3 second delay>
"there"

如果您不想将每个操作都放在自己的函数中,可以使用协程执行此操作:

import time
from functools import wraps

class Return(Exception):
    def __init__(self, value):
        self.value = value

def sleeper(func):
    """ Coroutine decorator that sleeps after every yield. 

    Any yield inside a function decorated with sleeper will
    result in a 3 second sleep after the operation being
    yielded has run.

    """
    @wraps(func)
    def wrapper(*args, **kwargs):
        def execute(gen):
            try:
                x = next(gen)
                time.sleep(3)
                while True:
                    x = gen.send(x)
                    time.sleep(3)
            except (Return, StopIteration) as e:
                return getattr(e, "value", None)
        gen = func(*args, **kwargs)
        return execute(gen)
    return wrapper

def f():
    print "should sleep"
    return "abc"

def g(val):
    print "should also sleep"
    return "%s-def" % (val,)

def h():
    print "this won't sleep"
    return "ghi"

@sleeper
def test():
    z = yield f()
    print "hey there, got %s" % (z,)
    y = yield g(z)
    print "ok: %s" % (y,)
    l = h()
    print "see %s" % (l,)
    z = yield f()
    print "done %s" % z
    raise Return("all done") # You can use return "all done" if you have Python 3.x


if __name__ == "__main__":
    final = test()
    print "final is %s" % final

输出:

should sleep
<3 second sleep>
hey there, got abc
should also sleep
<3 second sleep>
ok: abc-def
this won't sleep
see ghi
should sleep
<3 second sleep>
done abc
final is all done

使用此方法,使用sleeper协程装饰的任何方法都会在调用yield之后的任何方法后休眠。所以在你的情况下,而不是调用

driver.find_element_by_name("Account").click()

你会打电话给

yield driver.find_element_by_name("Account").click()

唯一的限制是您必须在使用sleeper修饰的函数内部之后要休眠的所有调用,并且如果您正在使用Python 2并且想要return来自装饰函数的内容,您需要使用raise Return(value)而不是return value。在Python 3.x上,return value可以正常工作。