硒(Java):从禁用的输入文本字段中检索值

时间:2018-07-17 13:20:52

标签: javascript java html css selenium

我正在尝试使用Java中的Selenium从输入字段中检索值。这是相关的HTML代码:

<input class="form-control input-sm " id="NameInputID" type="text" maxlength="16" name="NameInput" value="TheValueWanted" readonly="">

我尝试过:

driver.findElement(By.id("NameInputID")).getText();

driver.findElement(By.id("NameInputID")).getAttribute("value");

没有一个返回值(空白文本)。我该如何处理?

谢谢!

2 个答案:

答案 0 :(得分:1)

您可以通过JavascriptExecutor进行尝试:

Thread.sleep(3) // add a pause to wait until value of the element will be rendered
JavascriptExecutor je = (JavascriptExecutor) driver;
String script = "return document.getElementById('NameInputID').getAttribute('value');");
String value = je.executeScript(script);

答案 1 :(得分:0)

根据您共享的HTML来从输入字段中提取,即 TheValueWanted ,您需要更具体地使用Locator Strategy,并且需要诱使 WebDriverWait 使元素可见,您可以使用以下任一解决方案:

  • cssSelector

    String myText = new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("input.form-control.input-sm#NameInputID"))).getAttribute("value");
    
  • xpath

    String myText = new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//input[@class='form-control input-sm' and @id='NameInputID']"))).getAttribute("value");
    
相关问题