Home > Software design >  How to automate accept cookies pop-up from java app using Selenium
How to automate accept cookies pop-up from java app using Selenium

Time:02-15

The app is going to load the system default browser, load a special website, and then login automatically

import java.awt.Desktop;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class theurl {
public static void main(String[] args) {
    String url = "http://www.playok.com/en/spades/";
    if(Desktop.isDesktopSupported()){
        Desktop desktop = Desktop.getDesktop();
        try {
            desktop.browse(new URI(url));
        } catch (IOException | URISyntaxException e) {
            e.printStackTrace();
        }
    }else{
        Runtime runtime = Runtime.getRuntime();
        try {
            runtime.exec("xdg-open "   url);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

But before trying to login, first the cookies should be accepted automatically; is there a simple way to do it rather than using an external library? if not, which library can do the job

I tried this code, but didnt help:

WebDriver Driver = new ChromeDriver();
Driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
String url = "http://www.playok.com/en/spades/";
Driver.get(url);
Driver.findElement(By.id("cookie_action_close_header")).click();
System.out.println("completed");

CodePudding user response:

To click() on the element you need to induce WebDriverWait for the elementToBeClickable() and you can use either of the following locator strategies:

  • cssSelector:

    Driver.get("http://www.playok.com/en/spades/");
    new WebDriverWait(Driver, 20).until(ExpectedConditions.elementToBeClickable(By.cssSelector("button.ckbut.but0"))).click();
    
  • xpath:

    Driver.get("http://www.playok.com/en/spades/");
    new WebDriverWait(Driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//button[@class='ckbut but0' and text()='ACCEPT']"))).click();
    
  • Related