如何使用 Selenium 关闭 cookie 横幅

How to close the cookie banner using Selenium

提问人:Sheriff Sulemana 提问时间:8/5/2023 最后编辑:undetected SeleniumSheriff Sulemana 更新时间:8/6/2023 访问量:92

问:

此页面上有一个 cookie,我尝试使用 selenium java 和 testNG 关闭它,但没有关闭。网址 https://hausrat.allianz.de/

以下是我的代码:

public void closeCookieNotification() {//*[@id="onetrust-accept-btn-handler"]
        try {
            // Check if the cookie notification element is present
            WebElement cookieNotification = driver.findElement(By.xpath("//*[@id=\"onetrust-accept-btn-handler\"]"));

            // Close the cookie notification if present
            if (cookieNotification.isDisplayed()) {
                WebElement closeButton = driver.findElement(By.xpath("//*[@id=\"onetrust-accept-btn-handler\"]"));
                closeButton.click();
            }
        } catch (Exception e) {
            // Cookie notification not present or error occurred while closing, ignore
            System.out.println(e.getMessage());
        }
    }
java selenium-webdriver xpath css-selectors webdriverwait

评论

0赞 pcalkins 8/5/2023
为此,您可能需要使用 WebDriverWait。
0赞 Sheriff Sulemana 8/5/2023
您认为 WebdriverWait 在哪里合适。因为这是在 Test 类中实例化的类中,所以你在哪里是理想的
0赞 pcalkins 8/5/2023
这些类型的提示通常通过 Javascript 填充,这意味着 Selenium 不知道等待它们出现。这时,您需要在进行驱动程序调用以查找元素时使用 WebDriverWait。如今,大多数站点都非常繁重 JS,因此作为一般规则,对于涉及 DOM 的所有驱动程序调用,请始终使用 WebDriverWait。一个例外是在使用 .get() 调用之后,因为在这种情况下,Selenium 将等待页面加载。(使用它没有坏处,因为如果找到该元素,它几乎会立即返回。

答:

1赞 Yaroslavm 8/5/2023 #1

在这种情况下,您应该使用,直到出现同意模式。 立即执行,并且不会在站点加载后直接显示同意。WebDriverWaitfindElement

您可以尝试以下代码:

WebDriverWait wdwait = new WebDriverWait(driver, 10);

driver.get("https://www.allianz.de/recht-und-eigentum/hausratversicherung/");
WebElement consent = wdwait.until(ExpectedConditions.visibilityOfElementLocated(By.id("onetrust-accept-btn-handler")));
consent.click();
wdwait.until(ExpectedConditions.invisibilityOf(consent));
1赞 undetected Selenium 8/6/2023 #2

该元素是一个动态元素,因此要单击可单击的元素,您需要为 elementToBeClickable() 诱导 WebDriverWait,并且可以使用以下任一定位器策略

  • 使用 id

    driver.get("https://hausrat.allianz.de/");
    new WebDriverWait(driver, Duration.ofSeconds(10)).until(ExpectedConditions.elementToBeClickable(By.id("onetrust-accept-btn-handler"))).click();
    
  • 使用 cssSelector

    driver.get("https://hausrat.allianz.de/");
    new WebDriverWait(driver, Duration.ofSeconds(10)).until(ExpectedConditions.elementToBeClickable(By.cssSelector("button#onetrust-accept-btn-handler"))).click();
    
  • 使用 xpath

    driver.get("https://hausrat.allianz.de/");
    new WebDriverWait(driver, Duration.ofSeconds(10)).until(ExpectedConditions.elementToBeClickable(By.xpath("//button[@id='onetrust-accept-btn-handler']"))).click();