JavaScriptexecutor setAttribute value on selenium

随声附和 提交于 2019-12-20 04:10:06

问题


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 code

<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>

Selenium Code

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"));

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

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


回答1:


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"));


来源:https://stackoverflow.com/questions/42439570/javascriptexecutor-setattribute-value-on-selenium

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!