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

Pylance未识别Selenium的TimeoutException及ConnectionRefusedError导入报错

问题解决方案

一、ConnectionRefusedError 导入与运行时报错处理

  1. 修正导入逻辑
    ConnectionRefusedError 是 Python 标准库的异常类,并非 Selenium 内置,无需从 Selenium 导入。直接捕获标准库异常即可:
from selenium.common.exceptions import WebDriverException
import errno

try:
    # 你的Selenium操作代码
    driver.get("https://example.com")
except OSError as e:
    if e.errno == errno.ECONNREFUSED:
        print("连接被拒绝,请检查浏览器驱动状态")
except WebDriverException as e:
    print(f"Selenium操作异常: {e}")
  1. 排查连接拒绝的核心原因
    报错中的 MaxRetryError 说明 Selenium 无法连接到浏览器驱动(如 ChromeDriver、GeckoDriver),按以下步骤修复:
  • 确认浏览器驱动版本与本地浏览器版本完全匹配(例如 Chrome 120 需对应 ChromeDriver 120.x.x.x)
  • 正确配置驱动路径:可将驱动放入系统 PATH,或在代码中显式指定:
from selenium import webdriver
from selenium.webdriver.chrome.service import Service

# Selenium 4+ 推荐使用 Service 类指定驱动路径
driver = webdriver.Chrome(service=Service("/绝对路径/到/chromedriver"))
  • 关闭本地防火墙或代理,避免拦截本地驱动连接
  • 重启电脑释放被占用的端口资源

二、Pylance 无法识别 Selenium TimeoutException 的处理

  1. 安装官方类型提示包
    针对 Selenium 4.x,安装类型提示补充包:
pip install selenium-stubs
  1. 确认VS Code解释器环境
    点击VS Code左下角的Python解释器选择器,确保选中的是已安装Selenium的虚拟环境或全局环境,避免Pylance读取错误依赖
  2. 重启Pylance服务
    按 Ctrl+Shift+P(Windows/Linux)或 Cmd+Shift+P(Mac)打开命令面板,输入 Python: Restart Language Server 重启服务

内容的提问来源于stack exchange,提问作者hitesh goyal

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 17:16:01