【发布时间】:2011-04-11 07:19:59
【问题描述】:
我正在将一些测试从 Selenium 转移到 WebDriver。我的问题是我找不到 selenium.wait_for_condition 的等价物。 Python 绑定目前是否有此功能,还是仍在计划中?
【问题讨论】:
我正在将一些测试从 Selenium 转移到 WebDriver。我的问题是我找不到 selenium.wait_for_condition 的等价物。 Python 绑定目前是否有此功能,还是仍在计划中?
【问题讨论】:
目前无法将 wait_for_condition 与 WebDriver 一起使用。 python selenium 代码确实提供了用于访问旧 selenium 方法的 DrivenSelenium 类,但它不能执行 wait_for_condition。 The selenium wiki has some info on that.
最好的办法是使用 WebDriverWait 类。这是一个辅助类,它定期执行一个等待它返回 True 的函数。我的一般用法是
driver = webdriver.Firefox()
driver.get('http://example.com')
add = driver.find_element_by_id("ajax_button")
add.click()
source = driver.page_source
def compare_source(driver):
try:
return source != driver.page_source
except WebDriverException:
pass
WebDriverWait(driver, 5).until(compare_source)
# and now do some assertions
此解决方案绝不是理想的。在页面请求/响应周期延迟等待某些 ajax 活动完成的情况下,try/except 是必需的。如果在请求/响应周期中调用 compare_source get,它将抛出 WebDriverException。
【讨论】:
from selenium.webdriver.support import expected_conditions as ec,然后是 ec.visibility_of(elm)。它的返回对象是selenium.webdriver.support.expected_conditions.visibility_of,但我还没有弄清楚如何从中获得可见性。
这是我对 Greg Sadetsky 的回答,放入一个函数中:
def click_n_wait(driver, button, timeout=5):
source = driver.page_source
button.click()
def compare_source(driver):
try:
return source != driver.page_source
except WebDriverException:
pass
WebDriverWait(driver, timeout).until(compare_source)
它点击按钮,等待 DOM 改变然后返回。
【讨论】:
Java 绑定包含一个等待类。此类重复检查条件(之间有睡眠),直到达到超时。如果您可以使用普通 API 检测到您的 Javascript 的完成,则可以采用相同的方法。
【讨论】: