我刚开始使用 Selenium,并使用 Chrome 编写了一堆测试。然后我尝试使用 Firefox 运行相同的测试,但大多数都失败了。
我有一堆测试有点像这样:
1. Find link
2. Click link
3. Confirm the title of the new page matches what I expect
这在 Chrome 中运行良好,但在 Firefox 中,第 3 步似乎在浏览器有时间加载页面之前立即执行。如果我添加几秒钟的等待时间,所有测试都会通过,但我宁愿避免这种情况。
这是一个配置问题,还是有更好的方法来编写测试以帮助提高兼容性?
这些是在 Chrome 中运行但在 Firefox 中失败的测试的基础
link = driver.find_element_by_link_text(link_text)
link.click()
# Check if `driver.title` contains `title`
assert title in driver.title
在点击后插入一个 time.sleep(2) 使其工作。
(我在身份验证测试中遇到了同样的错误:填写表单,点击提交,确认用户被转发到正确的页面。在 Chrome 中,这通过了,在 Firefox 中,转发检查是针对登录页面完成的,因为浏览器仍未完成重定向到新页面。我收到测试失败的报告,一秒钟后浏览器呈现预期页面。)
请您参考如下方法:
您可以应用以下内容:
from selenium.webdriver.support.ui import WebDriverWait as wait
from selenium.webdriver.support import expected_conditions as EC
current_title = driver.title # get current title
link = driver.find_element_by_link_text(link_text)
link.click()
wait(driver, 10).until(lambda driver: driver.title != current_title) # wait for title to be different than current one
assert title in driver.title
