jam*_*ang 107 java selenium selenium-webdriver
在webapp的HTML中,有以下代码
<input type="text" name="prettyTime" id="prettyTime" class="ui-state-disabled prettyTime" readonly="readonly">
Run Code Online (Sandbox Code Playgroud)
页面上实际显示的是显示时间的字符串.
在Selenium Web Driver中,我有一个WebElement指向<input>使用的对象
WebElement timeStamp = waitForElement(By.id("prettyTime"));
Run Code Online (Sandbox Code Playgroud)
我希望得到的价值,WebElement换句话说,就是页面上印刷的内容.我尝试了所有的WebElementgetter,并没有找到用户看到的实际值.有帮助吗?谢谢.
pre*_*sto 191
尝试 element.getAttribute("value")
该text属性用于元素标记内的文本.对于输入元素,显示的文本不会被<input>标记包装,而是位于value属性内部.
注意:案件很重要.如果指定"值",则会返回"null"值.这至少对C#来说是如此.
小智 24
你可以这样做:
webelement time=driver.findElement(By.id("input_name")).getAttribute("value");
Run Code Online (Sandbox Code Playgroud)
这将为您提供在网页上显示的时间.
e1c*_*che 15
用硒2,
我通常这样写:
WebElement element = driver.findElement(By.id("input_name"));
String elementval = element.getAttribute("value");
Run Code Online (Sandbox Code Playgroud)
要么
String elementval = driver.findElement(By.id("input_name")).getAttribute("value");
Run Code Online (Sandbox Code Playgroud)
小智 5
如前所述,您可以执行类似的操作
public String getVal(WebElement webElement) {
JavascriptExecutor e = (JavascriptExecutor) driver;
return (String) e.executeScript(String.format("return $('#%s').val();", webElement.getAttribute("id")));
}
Run Code Online (Sandbox Code Playgroud)
但是正如您所看到的,您的元素必须具有id属性,并且页面上还必须具有jquery。
小智 5
按照@ragzzy的回答我用
public static string Value(this IWebElement element, IJavaScriptExecutor javaScriptExecutor)
{
try
{
string value = javaScriptExecutor.ExecuteScript("return arguments[0].value", element) as string;
return value;
}
catch (Exception)
{
return null;
}
}
Run Code Online (Sandbox Code Playgroud)
它工作得很好,不会改变DOM
jam*_*ang -3
这有点hacky,但是很有效。
我使用JavascriptExecutor并将 a 添加div到 HTML,并将其中的文本更改div为$('#prettyTime').val()
然后我使用 Selenium 来检索div并获取它的值。测试该值的正确性后,我删除了刚刚创建的div。