【问题标题】:Java selenium webdriver - get text out of a text fieldJava selenium webdriver - 从文本字段中获取文本
【发布时间】:2017-12-01 03:55:27
【问题描述】:

下面我尝试测试了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>

【问题讨论】:

  • 尝试使用By.id("Input")
  • 元素没有id;它只有名称和类型属性。
  • 你在第一句话中说text field whose id is "Input"。此外,如果您发布了您正在测试的页面的 HTML,也会有所帮助。
  • 我已经编辑了原始问题。
  • 即使得到答案,assertEquals(8,output); 也永远不会成功,因为int 永远不会等于String

标签: java selenium-webdriver


【解决方案1】:

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

element.getText() 用于获取标签内的文本节点,例如 &lt;tagname&gt;text&lt;/tagname&gt;.

但是,输入在标签(由节点表示)内没有文本,而是在 value 属性内;例如:&lt;input type="text" value="SomeValue"&gt;

所以,如果要获取元素内的节点文本,则必须使用element.getText(),但如果要获取输入的值,则必须使用element.getAttribute("value")

【讨论】:

  • 没有值属性。
  • 我相信这应该可行,请参阅stackoverflow.com/questions/7852287/…
  • 您好,@user1972031!如果没有 value 属性,则表示输入的 value 或 text 为空;在这种情况下,当您调用 element.getAttribute("value") 时,这将返回 null。
  • 您好,@user1972031!我很确定如果您的输入有一些可见的文本(这意味着您可以在浏览器的 html 页面中看到它),那么它具有该文本的 value 属性。如果没有 value 属性,则表示输入的 value 或 text 为空;在这种情况下,当您调用 element.getAttribute("value") 时,这将返回 null。如果是这种情况,那么您必须检查您的 SUT(被测系统),它没有正确设置输入的值,而不是您的 selenium 脚本。
  • @budi:您提供的链接“stackoverflow.com/questions/7852287/…”有一个很好的解释(下面逐字引用):-------- -------------------------------------------- 好吧,事实证明,如果缺少属性,它会尝试获取相应的属性。因此,您可以从 textarea 中获取“值”。 – CF ------------------------------------------------ --------------
猜你喜欢
  • 1970-01-01
  • 2013-10-09
  • 2015-12-12
  • 2016-06-13
  • 2013-10-08
  • 1970-01-01
  • 2019-05-20
  • 1970-01-01
相关资源
最近更新 更多