<input name="txtAnswer" class="box1" id="txtAnswer" type="text" maxlength="20">
My code:
driver.findElement(By.name("txtAnswer")).sendKeys("green");
<input name="txtAnswer" class="box1" id="txtAnswer" type="text" maxlength="20">
My code:
driver.findElement(By.name("txtAnswer")).sendKeys("green");
To locate the desired element you can use either of the following Locator Strategies:
Using cssSelector
:
driver.findElement(By.cssSelector("input#txtAnswer[class^='box'][name='txtAnswer']")).sendKeys("green")
Using xpath
:
driver.findElement(By.xpath("//input[starts-with(@class, 'box') and @id='txtAnswer'][@name='txtAnswer']")).sendKeys("green")
As you are seeing the error Unable to locate element you need to induce WebDruverWait for the element to be clickable and you can use either of the following solutions:
Using cssSelector
:
new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.cssSelector("input#txtAnswer[class^='box'][name='txtAnswer']"))).sendKeys("green")
Using xpath
:
new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//input[starts-with(@class, 'box') and @id='txtAnswer'][@name='txtAnswer']"))).sendKeys("green")
Id and class are two attributes for an web-element. to identify web element uniquely(one) id is used and to identify web elements use common properties like class, tag name etc.. so writing xpath with id attribute will give you unique match.
Answer: driver.findElement(By.id("txtAnswer")).sendKeys("green");