单击 'x' 关闭 youtube 弹出窗口 window 无法使用 Selenium WebDriver

Close youtube popup window by clicking 'x' is not working using Selenium WebDriver

尝试通过单击右上角的 'x' 按钮关闭 Youtube 弹出窗口 window,但我收到以下错误消息:

Caused by: org.openqa.selenium.ElementNotVisibleException: Element is not currently visible and so may not be interacted with

尝试了以下代码:

driver.findElement(By.className("close")).click();
driver.findElement(By.xpath("//button[@class='close']")).click();
driver.findElement(By.cssSelector("button[class='close']")).click();
JavascriptExecutor executor = (JavascriptExecutor) driver;
executor.executeScript("arguments[0].click();",
driver.findElement(By.className("close")));

HTML:

<div id="videoModal" class="modal fade in" aria-hidden="true" aria-labelledby="videoModal" role="dialog" tabindex="-1" style="display: block;">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-body">
<button class="close" aria-hidden="true" data-dismiss="modal" type="button">×</button>
<div>
<iframe width="100%" height="350" allowfullscreen="" src="https://www.youtube.com/embed/SQFKxxKMIxc?autoplay=1"/>
</div>

截图: https://i.stack.imgur.com/W3IXe.png

public Boolean closeVideoPopup(){
    try{
        driver.findElement(By.id("video-how-to")).click();
        driver.waitForPageLoad();
        driver.findElement(By.className("close")).click();
        return true;
    }
    catch(Exception e) {
        logger.info("Exception occurred: "+ e.getMessage().toString().substring(0, Integer.parseInt(TestConstants.ERRCHARCOUNT)));
    }
    return false;
}

这个选择器应该可以工作,但如果用适合的标记替换它会更有效:

driver.findElement(By.xpath("//*[contains(@class, 'close')]"));

或者,因为我们知道要查找的元素是 div:

 driver.findElement(By.xpath("//div[contains(@class, 'close')]"));

希望对您有所帮助。

可能其他元素与您的弹出窗口重叠。因此,您可以显式等待元素以使其可见。

 WebDriverWait wait=new WebDriverWait(driver, 90);
 wait.untill(ExpectedConditions.visibilityOf(driver.findElement(By.className("close")));

... 或找出重叠的元素并等待元素消失。

两种方式都可以尝试。

现在可以使用完整的 xpath

 driver.findElement(By.xpath(".//*[@id='videoModal']/div/div/div/button[@class='close']")).click();

使用 Sikuli 执行此操作的步骤:

在您的项目中添加 Sikuli jar 或在 pom.xml

中添加为依赖项
<dependency>
            <groupId>com.sikulix</groupId>
            <artifactId>sikulixapi</artifactId>
            <version>1.1.0</version>
</dependency>

使用Sikuli截取元素IDE。 安装和使用 Sikuli IDE 的步骤: http://www.sikuli.org/downloadrc3.html

编写以下代码:

Screen screen = new Screen();
Pattern image = new Pattern(filePath\xbutton.png");
screen.click(image);

屏幕的点击方法class将有助于点击元素