【问题标题】:JavascriptExecutor: setAttribute using nameJavascriptExecutor:使用名称设置属性
【发布时间】:2018-11-28 20:32:13
【问题描述】:

我想使用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

【问题讨论】:

    标签: javascript java html selenium-webdriver


    【解决方案1】:

    尝试了很多方法,前后都睡了,还是不行。

    最后对我有用的是:

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

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

    我猜setAttribute 也做了同样的事情,但是没有用。

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

    【讨论】:

    【解决方案2】:

    getElementsByName 返回一个 element 数组,在您的情况下,如果您只有一个名为 'ac118672' 的元素,您应该使用

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

    应该可以的

    【讨论】:

    • 它没有改变值,也没有给出任何错误。
    • 你需要找到正确的属性来保存你的值
    猜你喜欢
    • 2012-03-13
    • 1970-01-01
    • 2021-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-24
    • 2018-07-12
    • 2016-08-21
    相关资源
    最近更新 更多