【发布时间】:2015-11-08 22:26:09
【问题描述】:
我正在使用 Chrome 网络驱动程序,因为 Firefox 网络驱动程序在我的 Windows PC 上似乎存在问题。
在我去度假之前,我的 Django 功能测试运行良好,但现在它们抛出了各种错误。
有时,当我试图在页面上查找元素时:
selenium.common.exceptions.StaleElementReferenceException: Message: stale element reference: element is not attached to the page document
其他时候,验证 url 的尝试会失败,因为 Selenium 似乎正在从前一页读取 URL。失败点似乎会随着运行而变化,换句话说,测试的某些部分可以在执行之间在成功和不成功之间交替。但是,使用.click() 后似乎总是出现此问题。
在查看浏览器时,Selenium 似乎已成功导航到该页面,所以我想它只是太快地寻找项目——在它们存在于浏览器之前。
将implicitly.wait() 添加到我的 setUpClass 似乎没有帮助,但我可能使用错了。
我尝试了来自Harry Percival's site 的有希望的想法(如下),但 Selenium 只是在坐在被告知等待的页面上时超时。
from contextlib import contextmanager
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support.expected_conditions import \
staleness_of
class MySeleniumTest(SomeFunctionalTestClass):
# assumes self.browser is a selenium webdriver
@contextmanager
def wait_for_page_load(self, timeout=30):
old_page = self.browser.find_element_by_tag_name('html')
yield
WebDriverWait(self.browser, timeout).until(
staleness_of(old_page)
)
def test_stuff(self):
# example use
with self.wait_for_page_load(timeout=10):
self.browser.find_element_by_link_text('a link')
# nice!
还有其他人处理过这个吗?我应该遵循什么正确的方法来解决这个问题?
编辑: 发布的解决方案非常出色,并且真正清理了我的代码,因为我可以简单地将 .click() 添加到被调用的函数中,就像描述的那样。
以下是帮助我自定义的文档:
Documentation for the syntax for By for modification purposes.
Documentation for Selenium's Expected Conditions
注意:我使用术语“浏览器”代替驱动程序,我认为这是最初让我失望的原因。
【问题讨论】:
标签: python django selenium django-testing