本文介绍了硒上的JavaScriptexecutor setAttribute值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在IE11上执行硒自动化.现在换一个元素,说ele; ele.sendKeys(characters)无法直接工作.因此,我试图通过JavaScript Executor更改<input>标记的'value'属性.更改后,将通过ele.getAttribute('value')进行验证.但是那时候我得到的是值仍然像以前一样为null.而且我的测试也失败了.

I was executing a selenium automation on IE11. Now for an Element, say ele; ele.sendKeys(characters) are not working directly. So I was trying to change the 'value' attribute for that <input> tag through JavaScript Executor. Once I change that, I am verifying the same by ele.getAttribute('value'). But that time I am getting that the value is still null like earlier. And My test is also failing for the same.

HTML代码

<form id="upload" method="post" action="/upload" enctype="multipart/form-data" style="width: 90%">
<label for="uploadinputFile">
<br style="clear:all">
<input id="browse_file" class="bttn-primary" type="button" value="Browse">
<input id="file_input_browser" type="file" name="upload_File">
<div id="button">
<input id="submit" class="bttn-primary" type="submit" disabled="" value="Upload">
</div>
</form>

硒代码

WebElement brw=driver.findElement(By.id("file_input_browser"));
((JavascriptExecutor) driver).executeScript("document.getElementById('file_input_browser').setAttribute('value', 'new value for element')");
System.out.println("value:"+brw.getAttribute("value"));

我还使用了以下JavaScriptExecutor: ((JavascriptExecutor) driver).executeScript("arguments[0].setAttribute('value', '" +c+"')",brw);//c是字符串

I have also used following JavaScriptExecutor: ((JavascriptExecutor) driver).executeScript("arguments[0].setAttribute('value', '" +c+"')",brw);//c is a String

但是每次我得到brw.getAttribute("value")的输出都为空白/空

But Everytime I am getting output for brw.getAttribute("value") as blank/null

推荐答案

您必须在操作DOM之后而不是之前实例化WebElement.否则,存储的WebElement将不包含您要查找的信息,并将返回null.

You have to instantiate your WebElement after manipulating the DOM, not before. Otherwise the stored WebElement won't contain the information you are looking for and will return null.

driver.executeScript("document.getElementById('ID').setAttribute('value','NEW_VALUE');");
System.out.print("value: "+driver.findElement(By.id("ID")).getAttribute("value"));

这篇关于硒上的JavaScriptexecutor setAttribute值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-31 13:43