首页 > 解决方案 > JavascriptExecutor:使用名称设置属性

问题描述

我想使用的 HTMLJavascriptExecutor没有id. 它只包含name,classtag。其中只有一个name是唯一的,其余两个对于 DOM 中存在的许多其他 WebElement 是常见的。

我试过了:

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

jse().executeScript(javaScriptCode);

这给了我错误 document.getElementsByName(...).setAttribute is not a function,这很明显,因为按照此处https://www.w3schools.com/jsref/met_doc_getelementsbyname.aspdocument.getElementsByName的描述收集所有元素。

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

我拿的参考资料:

如何使用 JS Executor 编辑 HTML(删除只读)并在输入框中输入?

硒上的JavaScriptexecutor setAttribute值

标签: javascriptjavahtmlselenium-webdriver

解决方案


在尝试了很多方法之后,之前和之后睡觉,它没有工作。

最后对我有用的是:

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

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

我想setAttribute也做同样的事情,但它没有用。

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


推荐阅读