"Unable to locate element" 没有睡眠指令的错误

"Unable to locate element" error without sleep instruction

我有以下 Selenium 测试:

class MyTest extends PHPUnit_Extensions_Selenium2TestCase
{
    public function testFunction() {
        $this->url('https://mywebsiteurl.com');

        // ...
        // Several selenium actions here
        // ...

        $this->byId('form-submit-button')->click(); // Submit a form to another URL
        $this->byId('next')->click();
    }
}

随机地,我的测试失败并出现以下错误:

PHPUnit_Extensions_Selenium2TestCase_WebDriverException: Unable to locate element: {"method":"id","selector":"next"}
Command duration or timeout: 49 milliseconds
For documentation on this error, please visit: http://seleniumhq.org/exceptions/no_such_element.html
Build info: version: '2.40.0', revision: 'fbe29a9', time: '2014-02-19 20:54:28'
System info: host: 'selenium-server', ip: '15.121.50.61', os.name: 'Linux', os.arch: 'amd64', os.version: '3.2.0-4-amd64', java.version: '1.6.0_27'
Session ID: 4e7822e4-73dc-473e-8010-6717a04d243e
Driver info: org.openqa.selenium.firefox.FirefoxDriver
Capabilities [{platform=LINUX, acceptSslCerts=true, javascriptEnabled=true, browserName=firefox, rotatable=false, locationContextEnabled=true, version=24.6.0, cssSelectorsEnabled=true, databaseEnabled=true, handlesAlerts=true, browserConnectionEnabled=true, nativeEvents=false, webStorageEnabled=true, applicationCacheEnabled=true, takesScreenshot=true}]

当我看到生成的屏幕截图时,我可以看到按钮 "next" 出现在我的网页上,当我在调用 "click" 方法之前添加 "sleep(5)" 指令时,我的测试每次都通过。

你知道怎么解决我的问题吗?

我是 java 人..但是,根据你的问题,我建议你选择 implicit or explicit waits 来解决你的问题..

在谷歌搜索中,我发现了这段用于隐式等待的代码,您可以在此处使用它来解决您的问题:

$this->timeouts()->implicitWait(30000); 

将此添加到上面代码的顶部 $this->url('https://mywebsiteurl.com');。这将确保,每次 selenium 尝试定位一个元素时,它最多等待 30 秒。希望这对您有所帮助。