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

无法打印Swiggy注册提示信息,抛出NoAlertPresentException异常求助

解决Swiggy注册提示“Mobile number already exists”的打印问题

你遇到的NoAlertPresentException是因为页面上的提示不是浏览器原生alert弹窗,而是网页内嵌的普通DOM元素,代码里调用driver.switchTo().alert()自然会报错。

解决方案

  • 删除所有和alert相关的错误代码
  • 用显式等待确保提示元素加载完成(避免页面渲染延迟导致元素找不到)
  • 通过正确的定位方式获取提示文本并打印

修改后的完整代码

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import java.time.Duration;

public class Question14 {
    public static void main(String[] args) {
        ChromeOptions option = new ChromeOptions();
        option.addArguments("--remote-allow-origins=*");
        WebDriver driver = new ChromeDriver(option);
        driver.get("https://www.swiggy.com/");
        driver.manage().window().maximize();

        // 打开注册界面
        driver.findElement(By.className("r2iyh")).click();

        // 填写注册信息
        driver.findElement(By.name("mobile")).sendKeys("9876543210");
        driver.findElement(By.name("name")).sendKeys("Deepak");
        driver.findElement(By.name("email")).sendKeys("deepak@gmail.com");

        // 提交注册
        driver.findElement(By.className("a-ayg")).click();

        // 显式等待提示元素加载,超时时间10秒
        WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
        WebElement errorMsg = wait.until(ExpectedConditions.visibilityOfElementLocated(
                By.xpath("//div[text()='Mobile number already exists']")
        ));

        // 打印提示信息
        System.out.println(errorMsg.getText());

        // 关闭浏览器
        driver.quit();
    }
}

补充说明

  • 显式等待WebDriverWait会等待元素可见后再执行操作,避免因网络或页面渲染延迟导致的元素定位失败
  • 原代码中未完成的JavascriptExecutor部分若无实际用途可直接移除

内容的提问来源于stack exchange,提问作者Deepak Venkatesh

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 21:37:32