【问题标题】:Accepting cookies with Selenium in Java在 Java 中使用 Selenium 接受 cookie
【发布时间】:2022-01-16 09:37:20
【问题描述】:

我正在尝试抓取新闻网站,但无法使用 click() 方法接受“接受 cookie”弹出窗口。我可以在浏览器的 HTML 代码中看到按钮,但是当我使用 getPageSource() 方法时,按钮的代码不包括在内。

这是我的代码块

public class Webscraping {
  public static void main(String[] args) throws Exception{
    System.setProperty("webdriver.chrome.driver","C:\\Users\\Marvin\\Desktop\\Webscraping\\chromedriver.exe");
    
    //Pop Up blocken
    //ChromeOptions options = new ChromeOptions();
    //options.addArguments("disable-popup-blocking");
    
    WebDriver driver = new ChromeDriver();
    driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
    String url = "https://www.focus.de/";
    driver.get(url);
    Thread.sleep(5000);
    //HTML Code print
    System.out.println(driver.getPageSource());
  }
}

【问题讨论】:

    标签: java html selenium cookies


    【解决方案1】:

    click() 上的元素 Akzeptieren 在 url https://www.focus.de/ 中,因为所需的元素在 <iframe> 内,所以你必须:

    • 为所需的 frameToBeAvailableAndSwitchToIt 诱导 WebDriverWait
    • 为所需的 elementToBeClickable 诱导 WebDriverWait
    • 您可以使用以下任一Locator Strategies
      • 使用cssSelector

        driver.get("https://www.focus.de/");
        new WebDriverWait(driver, 10).until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.cssSelector("iframe[title='Iframe title']")));
        new WebDriverWait(driver, 10).until(ExpectedConditions.elementToBeClickable(By.cssSelector("button[title='Akzeptieren']"))).click();
        
      • 使用xpath

        driver.get("https://www.focus.de/");
        new WebDriverWait(driver, 10).until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.xpath("//iframe[@title='Iframe title']")));
        new WebDriverWait(driver, 10).until(ExpectedConditions.elementToBeClickable(By.xpath("//button[@title='Akzeptieren']"))).click();
        

    参考

    您可以在以下位置找到一些相关讨论:

    【讨论】:

    • 创建WebDriverWait 的多个实例对于相同的目的并不是一个好的做法。对于这个小用例尤其不是。创建一次实例,然后分配它是对变量的引用,并使用引用变量。
    • @cruisepandey 创建多个 WebDriverWait 实例不是一个好习惯:您是从哪里遇到这些的?如果让 GC 工作有什么问题?
    • 当您在 JAVA 中编写 new 时,在您的系统 RAM 中有一个名为堆的特定内存分配。在您编写new 的那一刻,将创建一个对象。要进行堆内存优化,不应为同一目的创建多个对象。它被称为空间复杂度。您可以在计算机设计和算法部分了解更多信息。
    • @cruisepandey 你还没有回答我的问题,为什么不让 GC 工作呢?你还期望 GC 做什么?我很想向您解释更多关于内存管理以及 GC 工作原理的信息。也许这超出了这个问题的范围。
    • @cruisepandey 给我一些时间我会解释的。
    猜你喜欢
    • 2021-08-13
    • 2023-01-30
    • 1970-01-01
    • 2023-01-24
    • 1970-01-01
    • 2021-07-20
    • 1970-01-01
    • 2022-01-09
    • 2021-05-01
    相关资源
    最近更新 更多