Selenium中的处理/接受cookie弹出窗口

问题描述

我正在尝试在主页上“接受cookie”,但是我的代码不起作用。我试图获取新的窗口句柄,然后为框架和“接受”按钮标识后续的Xpath,但是它永远无法工作。

package seleniumTestPack;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.*;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.webdriverwait;
import org.openqa.selenium.Cookie;


@SuppressWarnings("unused")
public class firstSelTest {
    public static void main(String[] args) throws InterruptedException {
        ChromeOptions options = new ChromeOptions();

        //Add chrome switch to disable notification - "**--disable-notifications**"
        options.addArguments("--disable-notifications");
        
        System.setProperty("webdriver.chrome.driver","C:\\Users\\vmyna\\Downloads\\chromedriver_win32\\chromedriver.exe");
        WebDriver driver = new ChromeDriver(options);
        
        driver.get("https://www.zyyah.com/homeowner-lifestyle-perfected-home-value-protected/");
        
        driver.manage().timeouts().implicitlyWait(30,TimeUnit.SECONDS);

        driver.switchTo().frame(0);
        driver.getwindowHandles();
        
        driver.switchTo().alert().accept();
        By cookies_accept = By.xpath("//*[@id=\"cookie-law-info-bar\"]");
        By cookies_gotIt = By.xpath("//*[@id=\"cookie_action_close_header\"]");
        webdriverwait wait = new webdriverwait(driver,10);
        wait.until(ExpectedConditions.elementToBeClickable(cookies_accept)).click();
        wait.until(ExpectedConditions.invisibilityOfElementLocated(cookies_accept));
        wait.until(ExpectedConditions.elementToBeClickable(cookies_gotIt)).click();

        driver.findElement(By.xpath("//*[@id=\'et-boc\']/div/div/div[4]/div/div/div[2]/div[1]")).click();
 
        Thread.sleep(10000);
        driver.quit();
        
    }
 }

解决方法

由于您的页面中没有框架,因此您无需切换框架。只需检查“接受Cookies”,然后单击即可。

driver.get("https://www.zyyah.com/homeowner-lifestyle-perfected-home-value-protected/");
 driver.manage().timeouts().implicitlyWait(30,TimeUnit.SECONDS);
driver.findElement(By.id("cookie_action_close_header")).click();

使用切换到框架:

https://www.browserstack.com/guide/handling-frames-in-selenium

警报的使用:

https://www.browserstack.com/guide/alerts-and-popups-in-selenium

,

以下代码对我有用。 “接受Cookie”按钮不在任何弹出窗口下。因此,此处没有框架或弹出窗口。在这里,我们只需要找到“接受Cookies”按钮,然后单击它即可。

    WebDriver Driver = new ChromeDriver();
    Driver.manage().timeouts().implicitlyWait(30,TimeUnit.SECONDS);
    String url = "https://www.zyyah.com/homeowner-lifestyle-perfected-home-value-protected/";
    Driver.get(url);
    Driver.findElement(By.id("cookie_action_close_header")).click();
    System.out.println("completed");