有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

javascript如何在SeleniumWebDriver中使用JavascriptExecuter设置属性值

我正在尝试为我的网站中所有相同类型的<img>标记设置一个attribute值,例如

<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 [

有没有人帮我这里出了什么问题,或者我还能做什么


共 (3) 个答案

  1. # 1 楼答案

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

    您正在使用^{}element上执行javascript,但是语法不正确,在^{}{}中,JavaScript将通过arguments魔术变量可用,就像是通过Function.apply调用函数一样,其中arguments必须是一个数字、一个boolean、一个String、^}等等

    你可以尝试以下方法:-

    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);
      }
    }
    
  2. # 2 楼答案

    您可以使用document来定位WebElement。在您的情况下,您已经找到了它。试一试

    jse.executeScript("arguments[0].setAttribute('style', 'display: none;')", e);
    
  3. # 3 楼答案

    有一个问题是,您像传递对象一样传递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;');" +
            "    }" +
            "}" );
    

    我没有经过测试就写了它,所以也许你应该编辑它;)