下面我尝试测试了1+7的加法运算;但不知道 如何获取属性“name”为“Input”的文本域的结果输出。
任何指针将不胜感激。
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>
最佳答案
尝试 driver.findElement(By.name("Input")).getAttribute("value")
.
element.getText()
用于获取标签内的文本节点,例如
<tagname>text</tagname>
.
但是,输入没有标签内的文本(由节点表示),而是在 value 属性内;例如:<input type="text" value="SomeValue">
.
所以,如果你想获取元素内的节点文本,你必须使用element.getText()
, 但如果你想获得输入的值,你必须使用 element.getAttribute("value")
.
关于Java selenium webdriver - 从文本字段中获取文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44791396/