You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Selenium ChromeDriver操作Pepperfry页面卡顿弹窗无法关闭求助

WebDriver Script Hangs After Sorting on Pepperfry.com Due to Unhandled Popups

Let’s tackle this frustrating popup issue that’s blocking your script. Those discount and registration modals are classic e-commerce annoyances—and they’re not standard JavaScript alerts (which is why your switchTo().alert() call didn’t work). Here’s a breakdown of the problem and how to fix it:

What’s Going Wrong?

  • Non-Alert Popups: The modals are HTML-based elements, not native browser alerts, so switchTo().alert() won’t detect them.
  • Overly Long Implicit Wait: Your script has an implicit wait set to 2000 seconds—that means it’ll hang for hours if an element doesn’t load, instead of failing fast.
  • No Wait for Dynamic Popups: The modals likely load after the sorting action completes, so your script tries to close them before they even exist.
  • Incorrect Sorting Steps: Your current code clicks the sort menu, then clicks the entire ul#sortBY element (which might not trigger the right action) before selecting the price option.

Step-by-Step Fixes

1. Fix the Implicit Wait Time

First, reduce that insane 2000-second wait to a reasonable value (like 20 seconds) so your script doesn’t hang indefinitely:

driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);

2. Use Explicit Waits for Popups

Explicit waits tell WebDriver to wait only until a specific element is ready, which is perfect for dynamic modals. Add these imports first:

import org.openqa.selenium.support.ui.WebDriverWait;
import org.openqa.selenium.support.ui.ExpectedConditions;
import java.util.ArrayList;
import java.util.Collections;
import org.testng.Assert;

3. Handle Multiple Popups

Check for both modals and close them if they appear. Wrap the close actions in a try-catch block to avoid errors if a popup doesn’t load (since some modals might be session-dependent).

4. Refine the Sorting Workflow

Make sure you’re clicking the correct elements to trigger the low-to-high sort, and add waits to ensure elements are interactable before clicking.

Revised Test Code

Here’s the updated Searchsort method with all fixes applied:

@Test
public void Searchsort() throws IOException {
    driver.get("https://www.pepperfry.com/");
    
    // Wait for search box to load, then search for Clocks
    WebElement searchBox = new WebDriverWait(driver, 20).until(
        ExpectedConditions.visibilityOfElementLocated(By.xpath("//input[@id='search']"))
    );
    searchBox.sendKeys("Clocks");
    searchBox.sendKeys(Keys.ENTER);
    
    // Trigger sort menu and select Price: Low to High
    WebElement sortButton = new WebDriverWait(driver, 20).until(
        ExpectedConditions.elementToBeClickable(By.xpath("//li[@id='curSortType']"))
    );
    sortButton.click();
    
    WebElement lowToHighOption = new WebDriverWait(driver, 20).until(
        ExpectedConditions.elementToBeClickable(By.xpath("//a[contains(text(),'Price: Low to High')]"))
    );
    lowToHighOption.click();
    
    // Handle discount popup (if present)
    try {
        WebElement discountPopupClose = new WebDriverWait(driver, 10).until(
            ExpectedConditions.elementToBeClickable(By.cssSelector("a.popup-close"))
        );
        discountPopupClose.click();
    } catch (Exception e) {
        System.out.println("Discount popup not found, skipping.");
    }
    
    // Handle registration popup (adjust selector if needed)
    try {
        WebElement regPopupClose = new WebDriverWait(driver, 10).until(
            ExpectedConditions.elementToBeClickable(By.cssSelector("div.close-icon"))
        );
        regPopupClose.click();
    } catch (Exception e) {
        System.out.println("Registration popup not found, skipping.");
    }
    
    // Now verify the first 8 items' price order
    List<WebElement> priceElements = new WebDriverWait(driver, 20).until(
        ExpectedConditions.visibilityOfAllElementsLocated(By.xpath("//span[@class='price']"))
    );
    
    // Extract and clean price values
    List<Double> prices = new ArrayList<>();
    for (int i = 0; i < Math.min(8, priceElements.size()); i++) {
        String priceText = priceElements.get(i).getText().replaceAll("[^0-9.]", "");
        prices.add(Double.parseDouble(priceText));
    }
    
    // Validate sort order
    List<Double> sortedPrices = new ArrayList<>(prices);
    Collections.sort(sortedPrices);
    Assert.assertEquals(prices, sortedPrices, "Prices are not sorted from low to high!");
}

Key Notes:

  • Adjust Selectors: The registration popup’s close button selector (div.close-icon) might need tweaking—inspect the element on the site to get the correct CSS selector or XPath.
  • Explicit Waits Over Implicit: Mixing explicit and implicit waits can cause unexpected delays, so consider relying primarily on explicit waits for critical actions.
  • Error Handling: The try-catch blocks ensure your script doesn’t fail if a popup doesn’t appear (which can happen based on user session or site updates).

内容的提问来源于stack exchange,提问作者Pratilipi Behera

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 09:08:17