【问题标题】:How to extract the value of an input field through getAttribute() or executeScript() method?如何通过 getAttribute() 或 executeScript() 方法提取输入字段的值?
【发布时间】:2018-08-21 12:25:59
【问题描述】:

存在 id 为条件的输入字段,getText()getAttribute() 不起作用

driver.findElement(By.id("condition")).getText() //is not working.. 

所以我在控制台尝试了

document.getElementById("condition").value //return the value. 

所以我尝试了

JavascriptExecutor jse = (JavascriptExecutor) driver;
System.out.println(jse.executeScript("document.getElementById(condition).value");
String value = jse.executeScript("document.getElementById(condition).value").toString();
AssertVerify(value, "15");

出现以下错误:

org.openqa.selenium.WebDriverException: JavaScript error (WARNING: The server did not provide any stacktrace information)

如何使用javascript获取值并分配给其他变量。

【问题讨论】:

  • 应该是"document.getElementById('condition').value",在condition周围加撇号。
  • 你是如何尝试getAttribute()的? getAttribute("value") 应该有效。
  • 正如@Guy 所说,对于输入文本框,您必须使用getAttribute("value") 来读取其中输入的字符串。对于其他控件,您应该使用getText(),它只能获取控件的只读文本。无需为您的情况使用executeScript

标签: java selenium selenium-webdriver webdriver getattribute


【解决方案1】:

您的代码试用近乎完美。您需要在单引号内传递元素的 id 属性,即 '...',如下所示:

String value = ((JavascriptExecutor)driver).executeScript("document.getElementById('condition').value").toString();

更新

由于您仍然无法通过executeScript() 方法检索,因此您需要诱导WebDriverWait 以使所需的元素可点击 你可以使用以下解决方案:

  • 使用getAttribute()检索文本:

    String myText = new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.id("condition"))).getAttribute("value");
    
  • 使用executeScript 检索文本:

    WebElement myElem = new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.id("condition")));
    String value = ((JavascriptExecutor)driver).executeScript("document.getElementById('condition').value").toString();
    

【讨论】:

  • 为元素 id 添加了单个但返回 null 但在控制台中运行时返回值。
  • 尝试第二个.. 第一个不起作用,因为我已经提到过
  • 试试更新的答案,让我知道状态。
猜你喜欢
  • 1970-01-01
  • 2019-04-23
  • 2023-03-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-08
  • 2013-10-14
  • 1970-01-01
相关资源
最近更新 更多