Selenium IDE脚本无法在Selenium Webdriver中运行

时间:2013-12-29 15:08:28

标签: java selenium selenium-webdriver

我创建了一些Selenium IDE脚本,然后导出了Java / Junit4 webdriver支持的脚本和简单的webdriver类。当我运行这些类时,测试用例唯一能做的就是打开正确的URL。在那之后,作为登录测试用例的测试用例根本找不到userName字段。我尝试过名字或者ID都可以。我甚至尝试添加一些方法来等待页面加载(实际上加载没有问题);我期待通过名称或id部分工作至少最后一个尝试块使用我在网上找到的方法继续寻找userName字段但如果我解决了frist两个尝试块我将不需要surfe。我尝试了一些在线堆栈流或其他论坛上的资源,但它有点令人困惑的是,IDE的简单脚本不会轻易地工作。

/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/

package com.mycomp.selenium.uatseleniumsuite.test;

/**
*
* @author sar
*/


import com.mycomp.selenium.uatseleniumsuite.login.PaymentsTabWithCssTest;
import static junit.framework.Assert.assertEquals;
import java.util.concurrent.TimeUnit;

import java.io.File;
import java.io.IOException;
import static junit.framework.Assert.assertTrue;

import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.StaleElementReferenceException;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.FluentWait;
import org.openqa.selenium.support.ui.Wait;
import org.openqa.selenium.support.ui.WebDriverWait;

public class TestloginSampleTest {

private String baseUrl;
private static WebDriver driver;
private ScreenshotHelper screenshotHelper;
static Logger logger = Logger.getLogger(TestloginSampleTest.class.getName());


@Before
public void openBrowser() {
baseUrl = "https://255.255.255.255:11115/myCompWebApp/login.go?siteLanguage=en&checked=true";
System.out.print("BASE URL IS  : "+baseUrl);
driver = new ChromeDriver();
driver.get(baseUrl);
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
screenshotHelper = new ScreenshotHelper();
}

@After
public void saveScreenshotAndCloseBrowser() throws IOException {
screenshotHelper.saveScreenshot("screenshot.png");
driver.quit();
}

@Test
public void UATLogin() throws IOException {
System.out.print("title : "+driver.getTitle());
assertEquals("The page title should equal mycomp at the start of the test.", "myCompOnline - Corporate", driver.getTitle());
try{
WebElement fuzoolPageCloseField = driver.findElement(By.id("splash-32856-close-button"));
System.out.print("fuzoolPageCloseField  : Found ");
fuzoolPageCloseField.click();
System.out.print("fuzoolPageCloseField  : Clicked ");
WebElement userNameField = driver.findElement(By.id("userName"));
System.out.print("userNameField  : Found ");
userNameField.sendKeys("myusername");
}catch( NoSuchElementException nse){
logger.error("EXCEPTION  by id: NoSuchElementException ");
System.out.print("EXCEPTION  by id: NoSuchElementException ");
nse.printStackTrace();
}catch(StaleElementReferenceException ser){
logger.error("EXCEPTION  : StaleElementReferenceException ");
System.out.print("EXCEPTION  : StaleElementReferenceException ");
ser.printStackTrace();

}


try{
WebElement userNameField = driver.findElement(By.name("userName"));
userNameField.sendKeys("myusername");
}catch( NoSuchElementException nse){
logger.error("EXCEPTION  By name : NoSuchElementException ");
System.out.print("EXCEPTION  BY name : NoSuchElementException ");
nse.printStackTrace();
}catch(StaleElementReferenceException ser){
logger.error("EXCEPTION  : StaleElementReferenceException ");
System.out.print("EXCEPTION  : StaleElementReferenceException ");
ser.printStackTrace();

}

try{
String myWindowHandle = driver.getWindowHandle();
driver.switchTo().window(myWindowHandle);
WebDriverWait wait = (WebDriverWait)new WebDriverWait(driver,10)
.ignoring(StaleElementReferenceException.class);
assertTrue("The page title should start with the search string after the search.",
(wait.until(new ExpectedCondition<Boolean>() { //last exception comes here for timeout
@Override 
public Boolean apply(WebDriver d) {
WebElement userNameField = driver.findElement(By.name("userName"));
userNameField.sendKeys("myusername");
return true;
}
})
));
}catch( NoSuchElementException nse){
logger.error("EXCEPTION after driver getwindowhandle : NoSuchElementException ");
System.out.print("EXCEPTION  : NoSuchElementException ");
nse.printStackTrace();
}catch(StaleElementReferenceException ser){
logger.error("EXCEPTION  : StaleElementReferenceException ");
System.out.print("EXCEPTION  : StaleElementReferenceException ");
ser.printStackTrace();

}



}

private class ScreenshotHelper {

public void saveScreenshot(String screenshotFileName) throws IOException {
File screenshot = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(screenshot, new File(screenshotFileName));
}
}

public void waitForElementPresent(final By by, int timeout){ 
WebDriverWait wait = (WebDriverWait)new WebDriverWait(driver,timeout)
.ignoring(StaleElementReferenceException.class); 
wait.until(new org.openqa.selenium.support.ui.ExpectedCondition<Boolean>(){ 
@Override 
public Boolean apply(WebDriver webDriver) { 
WebElement element = webDriver.findElement(by); 
return element != null && element.isDisplayed(); 
} 
}); 
}
public static WebElement getElementByLocator( final By locator ) {
//  LOGGER.info( "Get element by locator: " + locator.toString() );  
final long startTime = System.currentTimeMillis();
Wait<WebDriver> wait = new FluentWait<WebDriver>( driver )
.withTimeout(30, TimeUnit.SECONDS)
.pollingEvery(5, TimeUnit.SECONDS)
.ignoring( StaleElementReferenceException.class ) ;
int tries = 0;
boolean found = false;
WebElement we = null;
while ( (System.currentTimeMillis() - startTime) < 91000 ) {
//   LOGGER.info( "Searching for element. Try number " + (tries++) ); 
try {
we = wait.until( ExpectedConditions.visibilityOfElementLocated( locator ) );
found = true;
break;
} catch ( StaleElementReferenceException e ) {      
//    LOGGER.info( "Stale element: \n" + e.getMessage() + "\n");
}
}
long endTime = System.currentTimeMillis();
long totalTime = endTime - startTime;
if ( found ) {
//   LOGGER.info("Found element after waiting for " + totalTime + " milliseconds." );
} else {
//   LOGGER.info( "Failed to find element after " + totalTime + " milliseconds." );
}
return we;
}


}

“fuzoolPageCloseField”是一个窗口,它在脚本中加载并单击它有一个不同的名称,但我看到使用chrome defveloper工具它有一个不同的ID名称所以我在webdriver中使用它作为“splash -something”原始名称可以在IDE中运行。

堆栈跟踪如下:

由于驱动程序超时,堆栈跟踪在10秒间隔内出现NoSuchElementException异常,最后一个异常发生在line 110(wait.until(new ExpectedCondition<Boolean>() {

cd C:\NetBeansProject\Selenium\testseleniumsuite; JAVA_HOME=D:\\Java\\jdk1.6.0_45 M2_HOME=D:\\APIs\\Maven\\Binary\\apache-maven-3.0.4 cmd /c "\"\"D:\\APIs\\Maven\\Binary\\apache-maven-3.0.4\\bin\\mvn.bat\" -Dtest=com.mycomp.selenium.testseleniumsuite.test.TestloginSampleTest -DnetbeansProjectMappings= -Dmaven.ext.class.path=\"D:\\Program Files\\NetBeans 7.4\\java\\maven-nblib\\netbeans-eventspy.jar\" surefire:test\"\""
Running NetBeans Compile On Save execution. Phase execution is skipped and output directories of dependency projects (with Compile on Save turned on) will be used instead of their jar artifacts.
Scanning for projects...

------------------------------------------------------------------------
Building testseleniumsuite 1.0-SNAPSHOT
------------------------------------------------------------------------

--- maven-surefire-plugin:2.10:test (default-cli) @ testseleniumsuite ---
Surefire report directory: C:\NetBeansProject\Selenium\testseleniumsuite\target\surefire-reports

-------------------------------------------------------
 T E S T S
-------------------------------------------------------
Running com.mycomp.selenium.testseleniumsuite.test.TestloginSampleTest
BASE URL IS  : https://10.2.217.133:11115/myCompWebApp/login.go?siteLanguage=en&checked=trueStarting ChromeDriver (v2.8.241075) on port 21432
log4j:WARN No appenders could be found for logger (org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager).
log4j:WARN Please initialize the log4j system properly.
title : myCompOnline - CorporatefuzoolPageCloseField  : Found fuzoolPageCloseField  : Clicked    
  EXCEPTION  by id: NoSuchElementException org.openqa.selenium.NoSuchElementException: no such element
  (Session info: chrome=31.0.1650.63)
  (Driver info: chromedriver=2.8.241075,platform=Windows NT 6.1 SP1 x86) (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 20.06 seconds
For documentation on this error, please visit: http://seleniumhq.org/exceptions/no_such_element.html
Build info: version: '2.39.0', revision: '14fa800511cc5d66d426e08b0b2ab926c7ed7398', time: '2013-12-16 13:18:38'
System info: host: 'P5510041A', ip: '10.32.245.103', os.name: 'Windows 7', os.arch: 'x86', os.version: '6.1', java.version: '1.6.0_45'
Session ID: 62d2adad3c6cd4479b26a0f1fdab838e
Driver info: org.openqa.selenium.chrome.ChromeDriver
Capabilities [{platform=XP, acceptSslCerts=true, javascriptEnabled=true, browserName=chrome, chrome={userDataDir=C:\Users\5510041\AppData\Local\Temp\scoped_dir11832_12325}, rotatable=false, locationContextEnabled=true, version=31.0.1650.63, takesHeapSnapshot=true, cssSelectorsEnabled=true, databaseEnabled=false, handlesAlerts=true, browserConnectionEnabled=false, nativeEvents=true, webStorageEnabled=true, applicationCacheEnabled=false, takesScreenshot=true}]
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
    at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:193)
    at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:145)
    at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:554)
    at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:307)
    at org.openqa.selenium.remote.RemoteWebDriver.findElementById(RemoteWebDriver.java:348)
    at org.openqa.selenium.By$ById.findElement(By.java:220)
    at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:299)
    at com.mycomp.selenium.testseleniumsuite.test.TestloginSampleTest.UATLogin(TestloginSampleTest.java:75)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:28)
    at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:31)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:263)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:69)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:48)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:231)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:60)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:229)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:50)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:222)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:292)
    at org.apache.maven.surefire.junit4.JUnit4TestSet.execute(JUnit4TestSet.java:53)
    at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:123)
    at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:104)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at org.apache.maven.surefire.util.ReflectionUtils.invokeMethodWithArray(ReflectionUtils.java:164)
    at org.apache.maven.surefire.booter.ProviderFactory$ProviderProxy.invoke(ProviderFactory.java:110)
    at org.apache.maven.surefire.booter.SurefireStarter.invokeProvider(SurefireStarter.java:175)
    at org.apache.maven.surefire.booter.SurefireStarter.runSuitesInProcessWhenForked(SurefireStarter.java:107)
    at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:68)
EXCEPTION  BY name : NoSuchElementException org.openqa.selenium.NoSuchElementException: no such element
  (Session info: chrome=31.0.1650.63)
  (Driver info: chromedriver=2.8.241075,platform=Windows NT 6.1 SP1 x86) (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 20.05 seconds
For documentation on this error, please visit: http://seleniumhq.org/exceptions/no_such_element.html
Build info: version: '2.39.0', revision: '14fa800511cc5d66d426e08b0b2ab926c7ed7398', time: '2013-12-16 13:18:38'
System info: host: 'P5510041A', ip: '10.32.245.103', os.name: 'Windows 7', os.arch: 'x86', os.version: '6.1', java.version: '1.6.0_45'
Session ID: 62d2adad3c6cd4479b26a0f1fdab838e
Driver info: org.openqa.selenium.chrome.ChromeDriver
Capabilities [{platform=XP, acceptSslCerts=true, javascriptEnabled=true, browserName=chrome, chrome={userDataDir=C:\Users\5510041\AppData\Local\Temp\scoped_dir11832_12325}, rotatable=false, locationContextEnabled=true, version=31.0.1650.63, takesHeapSnapshot=true, cssSelectorsEnabled=true, databaseEnabled=false, handlesAlerts=true, browserConnectionEnabled=false, nativeEvents=true, webStorageEnabled=true, applicationCacheEnabled=false, takesScreenshot=true}]
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
    at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:193)
    at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:145)
    at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:554)
    at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:307)
    at org.openqa.selenium.remote.RemoteWebDriver.findElementByName(RemoteWebDriver.java:380)
    at org.openqa.selenium.By$ByName.findElement(By.java:305)
    at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:299)
    at com.mycomp.selenium.testseleniumsuite.test.TestloginSampleTest.UATLogin(TestloginSampleTest.java:91)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:28)
    at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:31)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:263)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:69)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:48)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:231)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:60)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:229)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:50)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:222)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:292)
    at org.apache.maven.surefire.junit4.JUnit4TestSet.execute(JUnit4TestSet.java:53)
    at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:123)
    at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:104)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at org.apache.maven.surefire.util.ReflectionUtils.invokeMethodWithArray(ReflectionUtils.java:164)
    at org.apache.maven.surefire.booter.ProviderFactory$ProviderProxy.invoke(ProviderFactory.java:110)
    at org.apache.maven.surefire.booter.SurefireStarter.invokeProvider(SurefireStarter.java:175)
    at org.apache.maven.surefire.booter.SurefireStarter.runSuitesInProcessWhenForked(SurefireStarter.java:107)
    at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:68)
Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 66.532 sec <<< FAILURE!

Results :

Tests in error: 
  UATLogin(com.mycomp.selenium.testseleniumsuite.test.TestloginSampleTest): Timed out after 10 seconds waiting for com.mycomp.selenium.testseleniumsuite.test.TestloginSampleTest$1@1e78fc6

Tests run: 1, Failures: 0, Errors: 1, Skipped: 0

------------------------------------------------------------------------
BUILD FAILURE
------------------------------------------------------------------------
Total time: 1:07.488s
Finished at: Sun Dec 29 17:54:50 AST 2013
Final Memory: 4M/15M
------------------------------------------------------------------------
Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.10:test (default-cli) on project testseleniumsuite: There are test failures.

Please refer to C:\NetBeansProject\Selenium\testseleniumsuite\target\surefire-reports for the individual test results.
-> [Help 1]

To see the full stack trace of the errors, re-run Maven with the -e switch.
Re-run Maven using the -X switch to enable full debug logging.

For more information about the errors and possible solutions, please read the following articles:
[Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoFailureException

希望任何人都可以提供帮助。

pS我还运行了webdriver支持的类,它们都在同一点上失败了(通过webdriver支持我的意思是你实例化一个selenium对象并使用它来进行测试但是甚至:selenium.click("id=splash-32856-close-button;");是不工作,至少这个si在驱动程序对象中工作)

先谢谢

2 个答案:

答案 0 :(得分:0)

查看Web浏览器中的HTML,找出它无法正常工作的原因。我怀疑你会发现ID正在发生变化,这就是为什么Selenium无法找到它们 - 因为它们不再存在了。

答案 1 :(得分:0)

我解决了我的问题。来自IDE的脚本在IDE中工作正常,当在java / Junit中导出时,语句就像

      driver.findElement(By.id("userName")).clear();
      driver.findElement(By.id("userName")).sendKeys("742817");

然而,我手动调试它并确保我进入它。我想我有一个iframe,这就是驱动程序无法看到元素的原因。

所以我搜索了iFrame,这很有用。

  WebElement iframeWebelement = driver.findElement(By.xpath("//html/body/form/...../tbody/tr/td/iframe"));
   System.out.println("iframeWebelement : Found ");

  driver.switchTo().frame(iframeWebelement);
   WebElement userNameField = driver.findElement(By.id("userName"));
    System.out.println("userName  : Found ");
        userNameField.sendKeys("myusername");
            System.out.println("userName  : entered data ");
这对我有用。我不知道iFrame是我需要切换到的东西。

希望这有助于使用iFrame的人。