[英]How to set an attribute value using JavascriptExecuter in Selenium WebDriver
I am trying to set an attribute
value for all same kind of <img>
tag in My website eg 我正在尝试为我的网站中所有相同类型的
<img>
标签设置attribute
值,例如
<img src="images/temp/advertisement.png">
and i wanted to set style="display:none"
so I will be able to hide them. 而且我想设置
style="display:none"
这样我就可以隐藏它们。
I have tried following method - 我尝试了以下方法-
List<WebElement> element = driver.findElements(By.tagName("img"));
for(WebElement e:element)
{
if(e.getAttribute(src).contains("images/temp/advertisement.png"))
{
jse.executeScript("document."+e+".setAttribute('style', 'display: none;')");
}
}
but getting an error 但出现错误
Exception in thread "main" org.openqa.selenium.WebDriverException: unknown error: Runtime.evaluate threw exception: SyntaxError: Unexpected token [
线程“主要” org.openqa.selenium.WebDriverException中的异常:未知错误:Runtime.evaluate引发异常:SyntaxError:意外令牌[
Is any one help what is wrong here or what other I can do? 有谁能帮到我这是什么问题,或者我可以做什么?
There is problem with that you pass e
like a object and there is called toString(), so final result is with [] etc... Another way could be something like this: 有一个问题,您像对象一样传递
e
,并称为toString(),所以最终结果是[]等。另一种方式可能是这样的:
jse.executeScript(
"var imgs = document.getElementsByTagName('img');" +
"for(var i = 0; i < imgs.length; i++) { " +
" if (imgs[i].getAttribute('src').indexOf('images/temp/advertisement.png') != -1) { " +
" imgs[i].setAttribute('style', 'display: none;');" +
" }" +
"}" );
I wrote it without test, so maybe you should edit it ;) 我写的是未经测试的,所以也许您应该编辑它;)
Exception in thread "main" org.openqa.selenium.WebDriverException: unknown error: Runtime.evaluate threw exception: SyntaxError: Unexpected token [
线程“主要” org.openqa.selenium.WebDriverException中的异常:未知错误:Runtime.evaluate引发异常:SyntaxError:意外令牌[
You are using JavascriptExecutor
to execute javascript
on an element
but syntactically incorrect, in executeScript
arguments
will be made available to the JavaScript via the arguments
magic variable, as if the function were called via Function.apply
where arguments
must be a number, a boolean
, a String
, WebElement
etc. 您正在使用
JavascriptExecutor
在element
上执行javascript
,但是在语法上不正确,在executeScript
arguments
将通过arguments
magic变量提供给JavaScript,就好像该函数是通过Function.apply
调用的,其中arguments
必须为数字, boolean
,一个String
, WebElement
等。
You can try as below :- 您可以尝试以下方法:
List<WebElement> element = driver.findElements(By.tagName("img"));
for(WebElement e:element) {
if(e.getAttribute("src").contains("images/temp/advertisement.png")){
jse.executeScript("arguments[0].style.display = 'none'", e);
}
}
You use document
to locate the WebElement
. 您使用
document
来定位WebElement
。 In your case you already located it. 在您的情况下,您已经找到了它。 Try
尝试
jse.executeScript("arguments[0].setAttribute('style', 'display: none;')", e);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.