Получение NoSuchElementException на webelement (Тот же webelement обнаруживается, но иногда я получаю исключение)

1

Я создал этот тестовый скрипт для тестирования веб-сайта. Проблема в том, что когда-нибудь я могу нажать кнопку редактирования, но иногда я получаю NoElementFoundException для той же кнопки. Я искал проблему такого же типа на форуме и изменил код в соответствии с рекомендацией, но не для них работал для меня. В прикрепленном изображении я обвел красную кнопку кнопкой, для которой я получаю исключение.

Изображение 174551

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']"). Возможно ли, что страница загружена не полностью или атрибут name меняется?
  • 2
    @ Ромски Я сделал это, и xpath может найти элемент. Я ставлю неявно ждать также, чтобы дать странице достаточно времени для загрузки .... Сэр, есть ли другое решение?
Теги:
selenium-webdriver
exception
nosuchelementexception

2 ответа

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)]"));
    }
});
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']"))
....

Ещё вопросы

Сообщество Overcoder
Наверх
Меню