如何使用 Selenium 和 Java 处理电子商务网站 https://www.firstcry.com 中的弹出窗口

How to handle the popup within the eCommerce website https://www.firstcry.com using Selenium and Java

`

    WebDriver Driver = null;
     WebDriverWait wait = null;
     @BeforeTest
      public void beforeTest() {
         System.setProperty("webdriver.chrome.driver","src\test\resources\drivers\chromedriver.exe");
         ChromeOptions options = new ChromeOptions();
         options.setExperimentalOption("excludeSwitches",Arrays.asList("disable-popup-blocking"));
         options.addArguments("--disable-popup-blocking");
         
         Driver = new ChromeDriver(options);
         Driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
         wait = new WebDriverWait(Driver, 25);
      }
    
    @Test(dataProvider = "dp")
  public void Test( String s) {
        String SearchWord = s;
        String url = "https://www.firstcry.com/";
        Driver.get(url);
        wait.until(ExpectedConditions.alertIsPresent());
        
        By popupdeny1 = By.xpath("//*[@id=\"deny\"]");
        By searchbox = By.id("search_box");
        By sortSelect = By.xpath("/html/body/div[5]/div[2]/div/div[2]/div[1]/div[2]/div[1]/div");
        By descendingPrice = By.xpath("/html/body/div[5]/div[2]/div/div[2]/div[1]/div[2]/div[1]/ul/li[4]/a");
        
        if(Driver.findElement(popupdeny1).isDisplayed())
            Driver.findElement(popupdeny1).click();`

出于学习目的,我正在自动化 firstcry 网页。 url 中有几个弹出窗口,我需要在搜索产品之前处理这些弹出窗口并根据价格

对项目进行排序

https://www.firstcry.com/

我什至在浏览器设置中添加了 Chrome 选项,但弹出窗口仍然出现...这是代码部分。 我尝试单击我的代码中的拒绝按钮,但以错误结束,提示无法找到该元素。

感谢任何帮助

click()文本为的元素urlhttps://www.firstcry.com/允许,因为所需的元素在 <iframe> 中,所以您必须:

  • 为所需的 frameToBeAvailableAndSwitchToIt.

    引入 WebDriverWait
  • 为所需的 elementToBeClickable.

    引入 WebDriverWait
  • 您可以使用以下任一项:

    • 使用 cssSelector:

      driver.get("https://www.firstcry.com/");
      new WebDriverWait(driver, 20).until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.cssSelector("iframe[title='webpush-onsite']")));
      new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.cssSelector("button#allow"))).click();
      
    • 使用 xpath:

      driver.get("https://www.firstcry.com/");
      new WebDriverWait(driver, 20).until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.xpath("//iframe[@title='webpush-onsite']")));
      new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//button[@id='allow']"))).click();
      
  • 浏览器快照: