繁体   English   中英

如何使用 Selenium 从 java 应用程序自动接受 cookies 弹出窗口

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

该应用程序将加载系统默认浏览器,加载一个特殊的网站,然后自动登录

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

但在尝试登录之前,首先应该自动接受 cookies; 有没有一种简单的方法来代替使用外部库? 如果没有,哪个图书馆可以完成这项工作

我试过这段代码,但没有帮助:

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

要在元素上单击() ,您需要为elementToBeClickable()诱导WebDriverWait ,您可以使用以下任一定位器策略

  • 选择器

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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