【问题标题】:Clicking on button that leads to pop-up Java Selenium Webdriver单击导致弹出 Java Selenium Webdriver 的按钮
【发布时间】:2018-04-11 05:26:03
【问题描述】:

我正在尝试编写一个程序来打开链接,单击贡献按钮,然后单击给予按钮。但是,当您实际单击“贡献”按钮时,它会打开一个弹出窗口,并且单击“贡献”按钮时我的程序无法执行任何操作。我怎样才能同时点击这两个按钮?

package com.demo.testcases;

import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.safari.SafariDriver;

public class FirstClass {

  public static void main(String[] args) throws InterruptedException {

    WebDriver driver = new SafariDriver();
    driver.manage().window().maximize();

    String giving = "https://givingday.northeastern.edu/campaigns/club-sports-3";

    driver.get(giving);

    Thread.sleep(3000);

    driver.findElement(By.linkText("CONTRIBUTE")).click();

    Thread.sleep(3000);

    driver.findElement(By.linkText("GIVE")).click();
  }
}

【问题讨论】:

    标签: java selenium selenium-webdriver webdriver


    【解决方案1】:

    根据您的问题,文本为 GIVE 的按钮是 <button> 标记,因此调用 By.linkText() 将不起作用。您可以使用以下任一 Locator Strategy 以及 _WebDriverWait_ 来单击元素:

    • cssSelector

      new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.cssSelector("button.vote_modal_redirect_btn.btn-primary "))).click();
      
    • xpath

      new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//button[@class='vote_modal_redirect_btn btn-primary' and contains(.,'Give')]"))).click();
      

    【讨论】:

      【解决方案2】:

      当您点击“贡献”按钮时,它会打开弹出窗口,所以请执行以下操作

      1. 使用getWindowHandles方法并切换到弹出窗口
      2. 切换到弹出窗口后,执行所需的操作(接受或关闭)。
      3. 使用窗口句柄返回原始/主窗口。
      4. 现在执行下一个操作。

      window 处理示例代码:

         // Store and Print the name of all the windows open                
      
              Set handles = driver.getWindowHandles();
      
              System.out.println(handles);
      
              // Pass a window handle to the other window
      
              for (String handle1 : driver.getWindowHandles()) {
      
                  System.out.println(handle1);
      
                  driver.switchTo().window(handle1);
      
                  }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-01-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-09-03
        • 1970-01-01
        相关资源
        最近更新 更多