Home > Software design >  How to send text to elements without id or value attribute using Selenium Java
How to send text to elements without id or value attribute using Selenium Java

Time:07-22

HTML:

<input type="text" placeholder="Enter name" >

I am trying to send text to this through Selenium. This is what I tried:

driver.findElement(By.cssSelector("input.form-control m-2[placeholder='Enter name']")).sendKeys("Test");

CodePudding user response:

form-control and m-2 are two different classes.

The selector should be input.form-control.m-2[placeholder='Enter name']

CodePudding user response:

Use xpath to interact with the web Element. The xpath will be -

//input[@placeholder='Enter name'][@type='text']

Use the following code -

WebElement inputName = driver.findElement(By.xpath("//input[@placeholder='Enter name'][@type='text']"));
inputName.sendKeys("Test");

CodePudding user response:

To send a character sequence to the desired element with placeholder as Enter name you can use either of the following Locator Strategies:

  • cssSelector:

    driver.findElement(By.cssSelector("input[placeholder='Enter name']")).sendKeys("Test");
    
  • xpath:

    driver.findElement(By.xpath("//input[@placeholder='Enter name']")).sendKeys("Test");
    

Ideally, to send a character sequence within the <input> element you need to induce WebDriverWait for the elementToBeClickable() and you can use either of the following locator strategies:

  • cssSelector:

    new WebDriverWait(driver, Duration.ofSeconds(10)).until(ExpectedConditions.elementToBeClickable(By.cssSelector("input[placeholder='Enter name']"))).sendKeys("Test");
    
  • xpath:

    new WebDriverWait(driver, Duration.ofSeconds(10)).until(ExpectedConditions.elementToBeClickable(By.xpath("//input[@placeholder='Enter name']"))).sendKeys("Test");
    
  • Related