You need to enable JavaScript to run this app. Python webbrowser库设默认Chrome却仍打开IE的代码调整咨询
优惠活动
大模型
产品
解决方案
定价
更多

Python webbrowser库设默认Chrome却仍打开IE的代码调整咨询

问题根源
  • Python内置的webbrowser模块在Windows平台的浏览器探测逻辑存在长期存在的兼容问题,会优先匹配系统中旧版Internet Explorer的程序关联配置,即便用户已经将系统默认浏览器设置为Google Chrome,也可能出现模块错调IE的情况。
  • 原代码直接调用webbrowser.open()接口,完全依赖模块的自动探测结果,没有强制指定目标浏览器,无法避免上述探测偏差。
可直接使用的修正代码

无需安装额外第三方库,仅需在原有逻辑基础上增加Chrome实例的手动注册流程,修正后的完整代码如下:

import webbrowser
import os

# 覆盖Chrome在Windows下的所有标准安装路径
chrome_path_pool = [
    r'C:\Program Files\Google\Chrome\Application\chrome.exe',
    r'C:\Program Files (x86)\Google\Chrome\Application\chrome.exe',
    os.path.expanduser(r'~\AppData\Local\Google\Chrome\Application\chrome.exe')
]

# 匹配实际存在的Chrome可执行文件,完成模块内的浏览器注册
for exe_path in chrome_path_pool:
    if os.path.exists(exe_path):
        webbrowser.register(
            'custom-chrome',
            None,
            webbrowser.BackgroundBrowser(exe_path)
        )
        break

web = input('What website would you like to open? i.e. pbskids.org')
# 自动补全URL协议头,避免无协议地址被识别为本地路径
if not web.startswith(('http://', 'https://')):
    web = f'https://{web}'

# 优先强制调用Chrome打开网页,匹配失败则退回系统默认浏览器逻辑
try:
    webbrowser.get('custom-chrome').open(web)
except webbrowser.Error:
    webbrowser.open(web)
调整点说明
  • 绕开webbrowser模块自带的自动探测流程,直接定位Chrome的可执行文件路径注册给模块,从根源上杜绝错调IE的问题。
  • 增加URL协议头自动补全逻辑,用户输入不带http/https前缀的站点地址时,不会出现浏览器路径识别错误。
  • 增加异常捕获兜底机制,若Chrome安装在自定义路径导致匹配失败,程序仍可正常调用系统默认浏览器打开网页,不会出现运行崩溃。

内容的提问来源于stack exchange,提问作者Marcus Lee

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.06 02:54:04