Search code examples
webdriverselenium-webdriver

Unable to locate an element using Selenium WebDriver 2.31 (JRE 7)


I'm trying to automate a scenario which books a bus ticket in a website. I'm using Selenium WebDriver with Eclipse and when i try to locate the element, i.e. 'Passenger name', no compilation errors, but while executing it shows an error such as "Exception in thread "main" org.openqa.selenium.NoSuchElementException: Unable to locate element: {"method":"xpath","selector":"//input[@name='i_passengerAge']"}".

HTML and Java code below, also i need an hasty solution for this.

My System Info:

  • Windows 7
  • Selenium WebDriver 2.31
  • Eclipse FW

HTML of the WebPage:

<input name="i_passengerName" id="i_passengerName" maxlength="30" class="inputclass pageRequired commonInputStyle" title="Please enter your name!" type="text">

<input name="i_passengerAge" id="i_passengerAge" maxlength="2" size="4" class="inputclass fillAge digits commonInputStyle" type="text">

My Automation Script:

WebElement PD_Name = driver.findElement(By.name("i_passengerName"));
PD_Name.sendKeys(new String[] {"Testing"});
PD_Name.submit();

WebElement PD_Age = driver.findElement(By.name("i_passengerAge"));
PD_Age.sendKeys(new String[] {"45"});
PD_Age.submit();

Solution

  • I hope you've tried to get the element with By.id, By.cssSelector or By.xpath.

    Watch out about the submit() method. Because it search automaticaly the form to send and sometimes it may fail. That's why i prefere the good old click().

    By.id :

    WebElement PD_Name=driver.findElement(By.id("i_passengerName"));
    PD_Name.sendKeys("Testing");
    PD_Name.click();
    

    By.xpath :

    WebElement PD_Name=driver.findElement(By.xpath("//input[@name='i_passengerName']"));
    PD_Name.sendKeys("Testing");
    PD_Name.click();
    

    For the cssSelector way, you can take a look here.

    Tell me if it improved. =)

    EDIT :

    Actually, there is no i_passengerGender