Search code examples
javaseleniumselenium-webdriverbrowser-automationselenium-firefoxdriver

Selenium Webdriver: How to bypass Google "accept-cookies" dialog box


I have a really simple Selenium WebDriver project in Java where I am using FireFox driver.

My goal is to navigate to Google's page (https://www.google.com) and when prompted to accept Cookies be able to click on the "I agree"-button to just get rid of it and continue the automation process further. But for some reason I just can't get the browser to locate it.

This is the instruction I am using currently:

package main;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

public class SeleniumGoogleTest {

    public static void main(String[] args) {

        WebDriver driver = new FirefoxDriver();
        driver.get("https://www.google.com");
        WebElement acceptButton = driver.findElement
        (By.xpath("/html/body/div/c-wiz/div[2]/div/div/div/div/div[2]/form/div/div[2]"));
        
    
    }
}


I don't know why the browser can't locate it and activate/enable that part of the page with neither Implicit wait or Explicit wait. Thread.sleep() method don't seem to be the solution either in this case.

The only error message I get when running the application is that of "Unable to locate the element".



A screenshot of where I get stuck


Is it that you actually can't automate some stuff with Selenium WebDriver or have I misunderstood some important concepts here?

Much grateful for all tips !


Solution

  • The popup is located on an iFrame, first you have to switch to the iFrame:

    driver.switchTo().frame(yourFrame);
    

    after you can find the accept button, and click it:

    driver.findElement(By.id("id")).click();