You need to enable JavaScript to run this app. Python Selenium基础脚本运行无报错闪退、安装配置问题如何解决
优惠活动
大模型
产品
解决方案
定价
更多

Python Selenium基础脚本运行无报错闪退、安装配置问题如何解决

Selenium基础脚本运行闪退无报错排查方案

问题描述

Selenium初学者运行极简测试代码时,Python窗口启动后会立刻自动关闭,全程无任何错误提示。

已执行操作

  • 安装Selenium:从PyPI站点下载安装包,解压后直接运行setup.py,安装过程无报错,安装结束CMD仅显示“请按任意键继续”
  • 准备WebDriver:已下载适配对应浏览器版本的驱动,分别是适配89版本Chrome的驱动、适配78.6.1esr(64位)Firefox的0.29.0版本geckodriver
  • 文件存放:将驱动程序、Selenium安装文件、待执行脚本放在同一目录下

已尝试的测试代码

基础运行代码

from selenium import webdriver

browser = webdriver.Firefox()
browser.get('https://www.google.com')

显式指定驱动路径的运行代码

from selenium import webdriver

browser = webdriver.Firefox('C:\Users\Bast01\Desktop\Python\Selenium Test\geckodriver.exe')
browser.get('https://www.google.com')

模块安装校验结果

在Windows 64位环境的Python 3.9.1交互式终端下,执行help("selenium")和help("Selenium")命令,均提示找不到对应模块的Python文档,完整输出如下:

Python 3.9.1 (tags/v3.9.1:1e5d33e, Dec  7 2020, 17:08:21) [MSC v.1927 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> help("selenium")
No Python documentation found for 'selenium'.
Use help() to get the interactive help utility.
Use help(str) for help on the str class.

>>> help("Selenium")
No Python documentation found for 'Selenium'.
Use help() to get the interactive help utility.
Use help(str) for help on the str class.

分步排查方案

1. 确认Selenium是否正确安装

help()命令找不到模块,首先说明Selenium未正确安装到当前使用的Python环境中:

  • 不要直接点击运行setup.py,改用pip安装命令,在CMD中执行:pip install selenium
  • 安装完成后,在Python交互式终端执行import selenium,无报错则说明安装成功,再执行help(selenium)可查看对应文档
  • 若安装时提示权限错误,可追加参数执行pip install selenium --user,安装到当前用户目录下避免权限问题

2. 修正WebDriver路径配置

即使把驱动放在脚本同目录,也可能因为Python环境路径识别问题导致调用失败:

  • 不要直接把驱动路径作为参数传入webdriver.Firefox(),该写法在Selenium 4.x版本中已废弃,正确的配置方式是使用Service类指定驱动路径
  • 正确的Firefox驱动配置代码示例:
from selenium import webdriver
from selenium.webdriver.firefox.service import Service as FirefoxService

# 替换为实际的geckodriver绝对路径,路径前加r避免转义问题
service = FirefoxService(executable_path=r"C:\Users\Bast01\Desktop\Python\Selenium Test\geckodriver.exe")
browser = webdriver.Firefox(service=service)
browser.get('https://www.google.com')

3. 解决窗口闪退看不到报错的问题

如果运行脚本时双击py文件启动,报错信息会随窗口关闭直接消失,无法查看错误:

  • 先通过CMD终端执行脚本,而非双击运行,报错信息会保留在终端中,可直接排查
  • 可在脚本末尾追加input("按回车退出"),让窗口不会自动关闭,方便查看运行状态

4. 版本兼容性校验

  • Firefox 78.6.1esr 与geckodriver 0.29.0版本存在兼容性问题,建议升级geckodriver到0.30.0以上版本,或更换为适配的Firefox版本
  • 若使用Chrome驱动,需确认当前安装的Selenium版本与Chrome 89版本适配,避免驱动版本不匹配导致的无报错闪退

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.27 20:54:07