【问题标题】:Is there any solution to bypass the cookie iframe by using selenium webdriver?有没有使用 selenium webdriver 绕过 cookie iframe 的解决方案?
【发布时间】:2020-12-29 01:19:32
【问题描述】:

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

https://www.hamburg.de/

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

  • 通过使用 iframe 的 ID sp_message_iframe_234327
  • 通过为 iframe 0 插入索引
  • 通过 WebElement WebElement element = driver.findElement(By.xpath("//body/div[6]/iframe[@src='https://cdn.privacy-mgmt.com/index.html?message_id=234327&consentUUID=b2cb90ea-dfdd-4655-b6b9-89117ff34893&requestUUID=ccb96546-c6b5-44e7-9869-438b32f7ad89&preload_message=true']")); driver.switchTo().frame(element); 调用 iframe

不幸的是,它们都不起作用。我总是遇到以下异常:

org.openqa.selenium.NoSuchFrameException

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

【问题讨论】:

    标签: java selenium xpath iframe css-selectors


    【解决方案1】:

    要点击 URL https://www.hamburg.de/ 内的 Alle akzeptieren,因为所需的元素位于 <iframe> 内,因此您必须:

    • 为所需的 frameToBeAvailableAndSwitchToIt 引入 WebDriverWait

    • 为所需的 elementToBeClickable 引入 WebDriverWait

    • 您可以使用以下任一Locator Strategies

      • 使用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();
        
    • 浏览器快照:


    参考

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-12-11
      • 1970-01-01
      • 2016-05-29
      • 2015-02-04
      • 1970-01-01
      • 1970-01-01
      • 2019-05-22
      相关资源
      最近更新 更多