简体   繁体   中英

How to automate accept cookies pop-up from java app using Selenium

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");

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM