当动态生成Value属性时,如何在Selenium Web驱动程序中使用java从<input>标记获取值

udi*_*08s 8 selenium selenium-webdriver

我试图操作的HTML:

<select id="GlobalDateTimeDropDown" class="combo"
    onchange="CalculateGlobalDateTime('Time',this.value)" name="GlobalDateTimeDropDown">
       <option value="+5.5" selected="selected"> … </option>
       <option value="+12"> … </option>
       <option value="+8"> … </option>
       <option value="+2"> … </option>
    </select>
    <input id="GlobalDateTimeText" class="combo" type="text" name="GlobalDateTimeText"       value="" style="width:215px;padding:2px;" readonly="readonly"></input>
Run Code Online (Sandbox Code Playgroud)

Java代码:

WebElement values=driver.findElement(By.id("GlobalDateTimeText")).getAttribute("Value");
System.out.println(values);
Run Code Online (Sandbox Code Playgroud)

输出:空白

Mar*_*nds 7

要选择输入值,您需要使用xpath选择器作为使用by.id将找到select元素,因为它们共享相同id- 这是不好的做法,因为它们确实应该是唯一的.无论如何,尝试:

driver.findElement(By.xpath("//input[@id='GlobalDateTimeText']")).getAttribute(??"value");
Run Code Online (Sandbox Code Playgroud)


Vin*_*nay 0

代码应该是这样的

WebElement dropDown = driver.findElement(By.id("GlobalDateTimeText"));
Select sel = new Select(dropDown);
List<WebElement> values = sel.getOptions();
for(int i = 0; i < values.size(); i++)
{
   System.out.println(values.get(i).getText());
}
Run Code Online (Sandbox Code Playgroud)

  • @udi08s 你可以尝试下面的代码吗?当您为 getAttribute("") 指定某些内容时,属性区分大小写。您已指定 Value 而不是 value WebElement value=driver.findElement(By.id("GlobalDateTimeText")).getAttribute("value"); System.out.println(值); (2认同)