如何使用javascript使用java使用selenium Webdriver设置所选Web元素的属性?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19934703/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use javascript to set attribute of selected web element using selenium Webdriver using java?
提问by Jasmine.Olivra
I want to use javascript to set attribute for selected element on webpage.
我想使用 javascript 为网页上的选定元素设置属性。
I have found 2 ways to set attribute using javascript
我找到了 2 种使用 javascript 设置属性的方法
1
1
WebDriver driver; // Assigned elsewhere
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("document.getElementByID('//id of element').setAttribute('attr', '10')");
2
2
WebElement element = driver.findElement(By.id("foo"));
String contents = (String)((JavascriptExecutor)driver).executeScript("return arguments[0].innerHTML;", element);
But I want to apply javascript to specific webelement which i have found using selenium webdriver
但我想将 javascript 应用到我使用 selenium webdriver 发现的特定 webelement
as an example i have select one link using selenium webdriver
例如,我选择了一个使用 selenium webdriver 的链接
driver.findElement(By.linkText("Click ME"))
Now I want to set attribute of this webelement using javascript
现在我想使用 javascript 设置这个 webelement 的属性
but I don't know how to combine both
但我不知道如何结合两者
please help me to find solution
请帮我找到解决方案
采纳答案by nilesh
Along the lines of:
沿着以下路线:
JavascriptExecutor js = (JavascriptExecutor) driver;
WebElement element = driver.findElement(By.linkText("Click ME"));
js.executeScript("arguments[0].setAttribute('attr', '10')",element);