2017-06-27 244 views
0

我尝试测试下面1 + 7的加法操作;但不知道 如何获得属性“name”为“Input”的文本字段的结果输出。Java selenium webdriver - 从文本字段中获取文本

任何指针,将不胜感激。


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代码下面列出:


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

尝试使用'By.id(“Input”)' –

+0

元素没有id;它只有名称和类型属性。 – user1972031

+0

你说在第一句中的文本字段的id是“Input”。另外,如果您发布了正在测试的网页的HTML,它将会有所帮助。 –

回答

4

尝试driver.findElement(By.name("Input")).getAttribute("value")

element.getText()用于获取标签内的文本节点,例如 <tagname>text</tagname>

但是,输入在标签(由节点表示)内没有文本,但在值属性内部;例如:<input type="text" value="SomeValue">。因此,如果您想要获取元素中的节点文本,则必须使用element.getText(),但是如果要获取输入值,则必须使用element.getAttribute("value")

+0

没有价值属性。 – user1972031

+1

我相信这应该工作,请参阅https://stackoverflow.com/questions/7852287/using-selenium-web-driver-to-retrieve-value-of-a-html-input –

+0

你好,@ user1972031! 如果没有任何值属性,则表示输入的值或文本为空;在这种情况下,当你调用element.getAttribute(“value”)时,这将返回null。 – Thisisalexis

相关问题