2017-06-27 179 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

相關問題