在 Selenium 中单击 link 后让 Firefox 等待新页面加载?

Getting Firefox to wait for new page to load after clicking a link in Selenium?

我刚开始使用 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