Tuesday, September 27, 2016

How to enter text in text field in selenium webdriver

 If you are new to Selenium Webdriver, please follow the steps in below link to successfully setup Selenium Webdriver on your machine.
If you have already setup Selenium Webdriver, please follow the steps to click on a link or button.
1. Launch webpage where your link or button is available.
2. Open firepath tab in firebug console
3. Click on inspect mouse icon displayed on top left in firebug console
4. Now click on the text field you want to enter text using Selenium Webdriver
5. Once you have clicked on the text field, the Xpath text field in firepath tab will display a xpath value
6. Copy the xpath
7. Now add this xpath and add it into your code as displayed in below example.

Let's do it with an example to enter a new comment in this post

package <Your package name here>;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class <YourClassNameHere>{
public static void main(String[] args) throws InterruptedException 
WebDriver driver = new FirefoxDriver();
driver.findElement(By.xpath(".//*[@id='commentBodyField']")).sendKeys("I have successfully entered a text in comments section");  // Using sendKeys method to enter text
driver.findElement(By.xpath(".//*[@id='postCommentSubmit']")).click();  // clicking on Publish button
Thread.sleep(5000);  // Waiting for 5 seconds to see entered comment in section

1. To run above code in eclipse, you must have firefox version latest-2 installed on your machine and selenium-java dependency added in your pom.xml file.
2. This xpath is very elementary and can fail even if there are minor changes in webpage code. when learning more in selenium webdriver, we can create customized xpath which are smaller and more reliable to success.

If you still face any issue in running the code, write to me in comments section.

No comments:

Post a Comment