简体   繁体   中英

Java selenium webdriver - get text out of a text field

I tried to test the addition operation of 1 + 7 below; but don't know how to get the result output of the text field whose attribute "name" is "Input".

Any pointer would be appreciated.


package hw9;

import java.util.concurrent.TimeUnit;
import org.junit.*;
import static org.junit.Assert.*;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;

public class calculator {
  private WebDriver driver;
  private String baseUrl;

  @Before
  public void setUp() throws Exception {
    driver = new FirefoxDriver();
    baseUrl = "http://www.math.com/";
    driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
  }

  @Test
  public void testCalculator() throws Exception {
    driver.get(baseUrl + "/students/calculators/source/basic.htm");
    driver.findElement(By.name("one")).click();
    driver.findElement(By.name("plus")).click();
    driver.findElement(By.name("seven")).click();
    driver.findElement(By.name("DoIt")).click();

    String output = driver.findElement(By.name("Input")).getText();
    System.out.println("Output: " + output);  // **<--- Empty output**
    assertEquals(8,output);

  }

  @After
  public void tearDown() throws Exception {
      driver.quit();
  }
}

HTML of code in question is listed below:


      <td> 
        <div align="center"> <font size="+1"> 
          <input name="Input" type="text" size="16">
          </font></div>
      </td>

Try driver.findElement(By.name("Input")).getAttribute("value") .

element.getText() is used to get the text node inside a tag, for example <tagname>text</tagname> .

But, an input does not have the text inside the tag (represented by a node), but inside the value attribute; for example: <input type="text" value="SomeValue"> .

So, if you want to get the node text inside an element, you have to use element.getText() , but if you want to get the value of an input, you have to use element.getAttribute("value") .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM