javascript - 如何在 Selenium WebDriver 中使用 JavascriptExecuter 设置属性值

标签 javascript java selenium selenium-webdriver

我正在尝试设置 attribute所有同类的值(value) <img>我的网站中的标签,例如

<img src="images/temp/advertisement.png">

我想设置 style="display:none"这样我就可以隐藏它们。

我尝试过以下方法 -

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;')");
        }
 }

但出现错误

Exception in thread "main" org.openqa.selenium.WebDriverException: unknown error: Runtime.evaluate threw exception: SyntaxError: Unexpected token [

有人可以帮助这里出了什么问题吗?或者我还能做些什么?

最佳答案

Exception in thread "main" org.openqa.selenium.WebDriverException: unknown error: Runtime.evaluate threw exception: SyntaxError: Unexpected token [

您正在使用JavascriptExecutorexecuteScript 中的 element 上执行 javascript 但语法不正确arguments 将通过 arguments 魔术变量提供给 JavaScript,就好像该函数是通过 Function.apply 调用的,其中 arguments 必须是数字、 boolean 值字符串WebElement 等。

您可以尝试如下:-

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);
  }
}

关于javascript - 如何在 Selenium WebDriver 中使用 JavascriptExecuter 设置属性值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41464050/

相关文章:

java - Selenium - 从 .apk 文件获取应用程序版本

python - 在 Python 中使用 Selenium 单击图像抛出无效的 xpath

javascript - 从精简的 JavaScript 代码中查找正确的变量

javascript - 单击按钮时,不会引发 OnClientClick 事件

java - 为什么找不到 MIME 媒体类型 application/zip?

java - 开始使用 JDBC 的先决条件

javascript - 分享后关闭手机上的 FB 选项卡

javascript - 当用户调整布局大小时使图像调整大小

java - JDBC中如何知道DDL语句是否执行成功?

python - 如何使用 python selenium webdriver 在 Chrome 开发者工具控制台中进行 fetch 调用