首页 > 解决方案 > 有没有使用 selenium webdriver 绕过 cookie iframe 的解决方案?

问题描述

我在以下嵌入 iframe 的网站上接受 cookie 警报时遇到问题:

https://www.hamburg.de/

在此处输入图像描述

我尝试了很多方法来解决使用driver.switchTo().frame()- 方法的问题:

不幸的是,他们都没有工作。我总是遇到以下异常:

org.openqa.selenium.NoSuchFrameException

有没有人知道这个具体的例子可以正确打开 iframe?我在 Java 上使用 Selenium WebDriver 3.141.59,我的测试应该在 Mozilla Firefox (80.0.1) 和 Chromium (85.0.4183.102) 上执行。这两个浏览器是无头启动的。很高兴有任何帮助。

标签: javaseleniumxpathiframecss-selectors

解决方案


Alle akzeptieren要在 url https://www.hamburg.de/中单击,因为所需的元素在 a 内,<iframe>所以您必须:

  • 为所需的frameToBeAvailableAndSwitchToIt诱导WebDriverWait

  • 为所需的elementToBeClickable诱导WebDriverWait

  • 您可以使用以下任一定位器策略

    • 使用cssSelector

      driver.get("https://www.hamburg.de/");
      new WebDriverWait(driver, 10).until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.cssSelector("iframe[id^='sp_message_iframe']")));
      new WebDriverWait(driver, 10).until(ExpectedConditions.elementToBeClickable(By.cssSelector("button[aria-label='Alle akzeptieren']"))).click();
      
    • 使用xpath

      driver.get("https://www.hamburg.de/");
      new WebDriverWait(driver, 10).until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.xpath("//iframe[starts-with(@id, 'sp_message_iframe')]")));
      new WebDriverWait(driver, 10).until(ExpectedConditions.elementToBeClickable(By.xpath("//button[@aria-label='Alle akzeptieren']"))).click();
      
  • 浏览器快照:

汉堡


参考

您可以在以下位置找到一些相关的讨论:


推荐阅读