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

Selenium WebDriver(Java)中如何处理地址保存自动填充弹窗

解决Chrome地址保存弹窗及Selenium依赖问题

一、修复addUserProfilePreference报错的核心问题

你遇到的方法报错,是因为Selenium 4.x版本已弃用addUserProfilePreference方法,同时需要确保Maven依赖配置正确:

1. Maven依赖配置

在pom.xml中引入对应版本的Selenium依赖,保持版本与你使用的4.11.0一致:

<dependencies>
    <!-- Selenium Java核心依赖 -->
    <dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-java</artifactId>
        <version>4.11.0</version>
    </dependency>
    <!-- 可选:自动管理驱动版本(避免手动匹配Chrome与ChromeDriver版本) -->
    <dependency>
        <groupId>io.github.bonigarcia</groupId>
        <artifactId>webdrivermanager</artifactId>
        <version>5.4.1</version>
        <scope>test</scope>
    </dependency>
</dependencies>

2. 替换正确的偏好设置方法

Selenium 4.x中,ChromeOptions添加用户偏好需使用addPreference或setExperimentalOption方法,替代旧的addUserProfilePreference。

二、禁用Chrome地址保存弹窗的代码实现

以下两种写法均可实现禁用地址保存弹窗的效果:

写法一:逐个添加偏好配置

import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.chrome.ChromeDriver;
import io.github.bonigarcia.wdm.WebDriverManager;

public class DisableAddressPopup {
    public static void main(String[] args) {
        // 自动匹配并下载对应版本的ChromeDriver
        WebDriverManager.chromedriver().setup();
        
        ChromeOptions options = new ChromeOptions();
        // 禁用地址自动填充功能
        options.addPreference("autofill.profile_enabled", false);
        // 禁止地址相关的自动填充请求(2代表禁止权限)
        options.addPreference("profile.default_content_setting_values.autofill", 2);
        
        ChromeDriver driver = new ChromeDriver(options);
        // 后续业务代码...
    }
}

写法二:批量设置偏好映射

import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.chrome.ChromeDriver;
import io.github.bonigarcia.wdm.WebDriverManager;
import java.util.HashMap;
import java.util.Map;

public class DisableAddressPopup {
    public static void main(String[] args) {
        WebDriverManager.chromedriver().setup();
        
        ChromeOptions options = new ChromeOptions();
        Map<String, Object> prefs = new HashMap<>();
        prefs.put("autofill.profile_enabled", false);
        prefs.put("profile.default_content_setting_values.autofill", 2);
        options.setExperimentalOption("prefs", prefs);
        
        ChromeDriver driver = new ChromeDriver(options);
        // 后续业务代码...
    }
}

三、额外注意事项

  • 若仍有弹窗出现,可尝试添加全局禁用自动填充的配置:prefs.put("browser.autofill.enable", false);
  • 确保Chrome浏览器版本(116)与ChromeDriver版本完全匹配,使用WebDriverManager可自动完成版本匹配,无需手动下载驱动。

内容的提问来源于stack exchange,提问作者R K

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 17:12:47