Pylance未识别Selenium的TimeoutException及ConnectionRefusedError导入报错
问题解决方案
一、ConnectionRefusedError 导入与运行时报错处理
- 修正导入逻辑
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}")
- 排查连接拒绝的核心原因
报错中的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 的处理
- 安装官方类型提示包
针对 Selenium 4.x,安装类型提示补充包:
pip install selenium-stubs
- 确认VS Code解释器环境
点击VS Code左下角的Python解释器选择器,确保选中的是已安装Selenium的虚拟环境或全局环境,避免Pylance读取错误依赖 - 重启Pylance服务
按Ctrl+Shift+P(Windows/Linux)或Cmd+Shift+P(Mac)打开命令面板,输入Python: Restart Language Server重启服务
内容的提问来源于stack exchange,提问作者hitesh goyal
相关产品推荐
相关产品推荐

