JavascriptExecutor:使用名称的setAttribute

时间:2018-11-28 20:32:13

标签: javascript java html selenium-webdriver

我要使用JavascriptExecutor进行操作的HTML没有id。它仅包含nameclasstag。在这些name中,唯一的是唯一的,而其余两个对于DOM中存在的许多其他WebElement是通用的。

我尝试过:

String javaScriptCode = "document.getElementsByName('ac118672').setAttribute('value','00031454476543');";

jse().executeScript(javaScriptCode);

这给了我错误 document.getElementsByName(...).setAttribute is not a function显而易见,因为document.getElementsByName给出了https://www.w3schools.com/jsref/met_doc_getelementsbyname.asp所述的所有元素的集合。

那么还有其他方法可以使用JavascriptExecutor更改value属性的值吗?

我参考的内容:

How to edit HTML (remove readonly) and type in input box using JS Executor?

JavaScriptexecutor setAttribute value on selenium

2 个答案:

答案 0 :(得分:1)

尝试了多种方式之后,之前和之后都无法入睡。

最后对我有用的是:

DBSet<>

document.getElementsByName('ac118672')[0].value='00031454476543';

我猜jse().executeScript(document.getElementsByName('ac118672')[0].value='00031454476543');也做同样的事情,但是没有用。

我在Windows 7的最新版本的Chrome和Gecko Driver上对其进行了测试。

答案 1 :(得分:0)

getElementsByName返回一个元素数组,如果您只有一个名称为'ac118672'的元素,则应使用

document.getElementsByName('ac118672')[0].setAttribute

应该起作用