Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to type in textbox using Selenium WebDriver (Selenium 2) with Java?

enter image description here I am using Selenium 2. But after running following code, i could not able to type in textbox.

    package Actor;
import org.openqa.*;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.junit.*;
import com.thoughtworks.selenium.*;
//import org.junit.Before;
public class Actor {
  public Selenium selenium;
  public WebDriver driver;

  @Before
  public void setup() throws Exception{
  driver = new FirefoxDriver();
      driver.get("http://www.fb.com");
  }
  @Test
  public void Test() throws Exception{
      //selenium.type("id=gs_htif0", "test");
      System.out.println("hi");
      // driver.findElement(By.cssSelector("#gb_1 > span.gbts")).click();
          selenium.waitForPageToLoad("300000000");

          WebElement email=driver.findElement(By.id("email"));

          email.sendKeys("[email protected]");
          driver.findElement(By.id("u_0_b")).click();
  }
  @After
  public void Close() throws Exception{
      System.out.println("how are you?");
  }

}
like image 889
Naveen Chhaniwal Avatar asked May 10 '13 11:05

Naveen Chhaniwal


People also ask

How do you type in a text box using Selenium?

We can type in a textbox using Selenium webdriver. We shall use the sendKeys() method to type in the edit box. It is an in-built method in Selenium. Let us consider a text box where we shall enter some text.

How do I enter enter and text in Selenium?

You can simulate hit Enter key by adding "\n" to the entered text. For example textField. sendKeys("text you type into field" + "\n") .

How do I add text to a textbox without sendKeys?

We can input text in the text box without the method sendKeys with thehelp of the JavaScript Executor. Selenium executes JavaScript commands with the help of the executeScript method. The JavaScript command to be run is passed as parameter to the method.

What is the JavaScript function used to enter the text in textbox?

To enter the text into a textbox using javascript, we have two ways: FindElement(Javascript) + EnterText (Javascript)


1 Answers

This is simple if you only use Selenium WebDriver, and forget the usage of Selenium-RC. I'd go like this.

WebDriver driver = new FirefoxDriver();
WebElement email = driver.findElement(By.id("email"));
email.sendKeys("[email protected]");

The reason for NullPointerException however is that your variable driver has never been started, you start FirefoxDriver in a variable wb thas is never being used.

like image 119
aimbire Avatar answered Sep 28 '22 01:09

aimbire