2014-07-07 191 views
1

我已经创建了这个测试脚本来测试一个网站。问题是,有时我能够点击编辑按钮,但有时我得到NoElementFoundException为同一个按钮。我在论坛上搜索了相同类型的问题,并根据建议更改了代码,但其中没有一个适合我。在附图中,我用红色圈起了按钮,为此我得到了异常。在webelement上获取NoSuchElementException(相同的webelement被发现,但有时我得到异常)

enter image description here

import java.util.NoSuchElementException; 
import java.util.concurrent.TimeUnit; 
import org.openqa.selenium.*; 
import org.openqa.selenium.firefox.*; 
import org.openqa.selenium.interactions.Actions; 
import org.openqa.selenium.support.ui.Select; 
import org.testng.annotations.Test; 

public class MonsterUpdateNewProfile { 
    static WebDriver window=new FirefoxDriver(); 
    static WebElement wb; 
    static String[] data; 
    @Test(priority=2) 
    static public boolean isAlertExist(){ 
     boolean alert=false; 
     try{ 
      Alert alt= window.switchTo().alert(); 
      alert=true; 
      System.out.println("Text from alert is "+alt.getText()); 
      alt.dismiss(); 
     }catch(Exception e){ 
      System.out.println("No Alert"); 
      e.printStackTrace(); 
     } 
     return alert; 
    } 
    @Test 
    static void dropdown() throws InterruptedException { 
     wb=window.findElement(By.xpath("//div[@class='ns_menu_item_wrap ns_lt active']/a")); 
     Actions mouse=new Actions(window); 
     mouse.moveToElement(wb).perform(); 
     Thread.sleep(4000); 
     Select select=new Select(wb); 
     select.selectByIndex(1); 
     }//dropdown 
    @Test 
    public static void monster() throws InterruptedException { 
     try{ 
     //connecting to web site by sending address url 
     window.get("https://my.monsterindia.com/login.html?src=http://my.monsterindia.com/my_monster.html&rand=5257"); 
     window.manage().window().maximize(); 
     window.manage().timeouts().implicitlyWait(40, TimeUnit.SECONDS); 
     //finding username by using xpath 
     wb=window.findElement(By.id("BodyContent:txtUsername")); 
     //sending username 
     wb.sendKeys("[email protected]"); 
     //finding and sending password 
     window.findElement(By.id("BodyContent_txtPassword")).sendKeys("Ferrari2738"); 
     window.manage().timeouts().implicitlyWait(40, TimeUnit.SECONDS); 
     //finding and clicking on login button 
     window.findElement(By.name("submit")).click(); 
     //grtting the title of current page using getTitle() method 
     System.out.println(window.getTitle()); 
     window.manage().timeouts().implicitlyWait(40, TimeUnit.SECONDS); 
     window.findElement(By.name("cancel")).click(); 
     window.findElement(By.className("flyout_close")).click(); 
     //locating and clicking on update button which will open a new window 
     window.findElement(By.xpath("//img[@src='http://media.monsterindia.com/monster_2012/btn_update2.gif']")).click(); 
     window.manage().timeouts().implicitlyWait(40, TimeUnit.SECONDS); 
     //capturing the title of oldwindow or the window which we go after loging 
     //using getWindowHandle() method 
     String oldwindow=window.getWindowHandle(); 
     //by using for statement getting the title of new pop upwindow 
     //here we can use if or while statement as well using getWindowHandles() method 
     for(String newwindow : window.getWindowHandles()){ 
     //swithching to the new pop up using window.switchTo().window(passing newwindow as argument)  
     window.switchTo().window(newwindow);} 
     //getting title of new window using getTitle() method 
     System.out.println("NewWindow Title"+ window.getTitle()); 
     window.findElement(By.xpath(".//*[@id='edit_resume_section3_open' and not(@disabled)]")).click(); 
     window.manage().timeouts().implicitlyWait(40, TimeUnit.SECONDS); 
     System.out.println(window.findElement(By.xpath("//input[@name='title']")).getAttribute("value")); 
     window.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); 
     window.findElement(By.id("update")).click(); 
     window.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); 
     window.close(); 
     //switching to oldwindow or main window 
     //using switchTo().window(passing oldwindow url to it) 
     //url which we captured in String oldwindow=window.getWindowHandle() method 
     window.switchTo().window(oldwindow); 
     //getting the output of old window 
     System.out.println("OldWindow Title" + window.getTitle()); 
     //isAlertExist(); 
     //dropdown(); 
    }//try 
     catch(NoSuchElementException e){ 
      window.findElement(By.className("flyout_close")).click(); 
      window.findElement(By.xpath("//a[@href='http://my.monsterindia.com/view_resume.html?resid=51706134&mode=edit']/img")).click(); 
      window.manage().timeouts().implicitlyWait(40, TimeUnit.SECONDS); 
      window.findElement(By.id("edit_resume_section3_open")).click(); 
      window.manage().timeouts().implicitlyWait(40, TimeUnit.SECONDS); 
      System.out.println(window.findElement(By.xpath("//input[@name='title']")).getAttribute("value")); 
      window.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); 
      window.findElement(By.id("edit_resume_section3_close_other")).click(); 
      window.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); 
      //isAlertExist(); 
      dropdown(); 
     }//catch 
     catch(Exception e){ 
      e.printStackTrace(); 
      System.out.println("Got Acception"); 
      window.close(); 
     }//catch 
     finally{ 
      //dropdown(); 
      System.out.println("Finally Closing"); 
      window.close(); 
      window.quit(); 

     }//finally 
    }//main 
}//class 

Exception got for this code- 
    org.openqa.selenium.NoSuchElementException: Unable to locate element: {"method":"xpath","selector":"//input[@name='title']"} 
Command duration or timeout: 40.06 seconds 
For documentation on this error, please visit: http://seleniumhq.org/exceptions/no_such_element.html 
Build info: version: '2.39.0', revision: 'ff23eac', time: '2013-12-16 16:12:12' 
System info: host: 'omega-d52b83806', ip: '10.0.0.5', os.name: 'Windows XP', os.arch: 'x86', os.version: '5.1', java.version: '1.7.0_45' 
Session ID: f4dce968-0425-4ba1-8a62-4ebdff91edc8 
Driver info: org.openqa.selenium.firefox.FirefoxDriver 
Capabilities [{platform=XP, acceptSslCerts=true, javascriptEnabled=true, cssSelectorsEnabled=true, databaseEnabled=true, browserName=firefox, handlesAlerts=true, browserConnectionEnabled=true, webStorageEnabled=true, nativeEvents=false, rotatable=false, locationContextEnabled=true, applicationCacheEnabled=true, takesScreenshot=true, version=29.0.1}] 
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) 
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source) 
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source) 
at java.lang.reflect.Constructor.newInstance(Unknown Source) 
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.findElementByXPath(RemoteWebDriver.java:404) 
at org.openqa.selenium.By$ByXPath.findElement(By.java:363) 
at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:299) 
at MonsterUpdateNewProfile.monster(MonsterUpdateNewProfile.java:74) 
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) 
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) 
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) 
at java.lang.reflect.Method.invoke(Unknown Source) 
at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:84) 
at org.testng.internal.Invoker.invokeMethod(Invoker.java:714) 
at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:901) 
at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1231) 
at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:127) 
at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:111) 
at org.testng.TestRunner.privateRun(TestRunner.java:767) 
at org.testng.TestRunner.run(TestRunner.java:617) 
at org.testng.SuiteRunner.runTest(SuiteRunner.java:334) 
at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:329) 
at org.testng.SuiteRunner.privateRun(SuiteRunner.java:291) 
at org.testng.SuiteRunner.run(SuiteRunner.java:240) 
at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52) 
at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86) 
at org.testng.TestNG.runSuitesSequentially(TestNG.java:1224) 
at org.testng.TestNG.runSuitesLocally(TestNG.java:1149) 
at org.testng.TestNG.run(TestNG.java:1057) 
at org.testng.remote.RemoteTestNG.run(RemoteTestNG.java:111) 
at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:204) 
at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:175) 
Caused by: org.openqa.selenium.remote.ErrorHandler$UnknownServerException: Unable to locate element: {"method":"xpath","selector":"//input[@name='title']"} 
Build info: version: '2.39.0', revision: 'ff23eac', time: '2013-12-16 16:12:12' 
System info: host: 'omega-d52b83806', ip: '10.0.0.5', os.name: 'Windows XP', os.arch: 'x86', os.version: '5.1', java.version: '1.7.0_45' 
Driver info: driver.version: unknown 
at <anonymous class>.FirefoxDriver.prototype.findElementInternal_(file:///C:/DOCUME~1/OMEGA/LOCALS~1/Temp/anonymous591356915052066864webdriver-profile/extensions/[email protected]/components/driver_component.js:8860) 
at <anonymous class>.fxdriver.Timer.prototype.setTimeout/<.notify(file:///C:/DOCUME~1/OMEGA/LOCALS~1/Temp/anonymous591356915052066864webdriver-profile/extensions/[email protected]/components/driver_component.js:396) 
+4

首先,尝试运行针对该页面中的XPath来测试它实际上找到的元素。您可以使用Chrome控制台执行此操作 - $ x(“// input [@ name ='title']”)。有没有可能该页面没有完全加载,或名称属性不同? – Romski

+2

@Romski我做到了,xpath能够找到元素。我也隐含地等待,给页面足够的时间来加载....先生的其他解决方案? –

回答

0

发布一个答案,因为我无法工作,如何放在注释代码...

错误说,它无法找到的元素,所以无论是XPath的有问题,或者该元素不存在。你可以尝试让元素成为你的等待条件。

.... 
WebDriverWait wait = new WebDriverWait(webDriver, 30) 
window.findElement(By.id("...")).click(); 
wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//input[@name='title']"))) 
webDriver.findElement(By.xpath("//input[@name='title']")) 
.... 
0

请检查您的XPath” .//*[@id='edit_resume_section3_open”,而不是(@disabled)”的正确性。

如果它是正确的然后尝试等待这个元素,如果它是可用的,那么只需点击它。

您可以使用下面的代码来等待元素:

(new WebDriverWait(driver, 60)).until(new ExpectedCondition<WebElement>() { 
    public WebElement apply(WebDriver d) { 
     return d.findElement(By.xpath(".//*[@id='edit_resume_section3_open' and not(@disabled)]")); 
    } 
});