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

运行Selenium Python脚本返回exit code 0无输出、浏览器不启动

问题原因

你遇到的无控制台输出、浏览器不启动、进程返回exit code 0的问题,核心是代码没有实际执行测试逻辑,同时存在几处写法错误:

  • 只定义了test_google函数,没有添加调用逻辑。直接运行Python文件时,解释器只会完成函数和导入的定义,不会运行函数内部的代码,执行完所有顶层代码后就直接退出,所以返回exit code 0,没有任何实际操作。
  • 缺少关键导入语句:代码里没有导入selenium.webdriver模块,就算执行函数也会直接抛出NameError。
  • Selenium 4.0及以上版本不再支持直接将驱动路径作为参数传入webdriver.Chrome(),需要借助Service类传递驱动路径,否则会触发参数错误。
  • 如果是用pytest命令运行脚本,默认会屏蔽print输出,需要加额外参数才能看到打印内容。
修复步骤
  1. 补全缺失的导入,删除未使用的冗余导入
  2. 调整Chrome驱动的初始化写法,适配高版本Selenium API
  3. 要么添加脚本入口直接调用测试函数,要么用正确的pytest命令执行
  4. 注意:直接访问https://www.google.com/默认页面标题是Google,不是你写的登录页标题,原断言大概率会失败,可以根据实际访问的页面调整断言逻辑
修复后完整代码
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from webdriver_manager.chrome import ChromeDriverManager
import time


def test_google():
    driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()))
    driver.implicitly_wait(5)
    driver.get("https://www.google.com/")
    print(driver.title)
    # 按需调整断言逻辑,访问google首页默认标题不是登录页文案
    # assert driver.title == 'Sign in – Google accounts'
    driver.quit()


# 直接运行当前py文件时会执行测试逻辑
if __name__ == "__main__":
    test_google()
运行方式
  • 普通脚本运行:直接执行这个py文件即可,会自动启动Chrome浏览器,访问谷歌首页,控制台打印页面标题后自动关闭浏览器
  • pytest方式运行:在脚本所在目录执行命令 pytest 你的脚本文件名.py -s,其中-s参数是为了关闭pytest的输出捕获,正常显示print的打印内容
补充说明
  • 如果你使用的Selenium版本为4.6及以上,框架内置了Selenium Manager能力,会自动匹配、下载对应版本的浏览器驱动,不需要额外使用webdriver_manager,初始化驱动时直接写driver = webdriver.Chrome()即可正常运行。
  • 脚本执行完记得调用driver.quit()关闭浏览器进程,避免残留后台Chrome进程占用资源。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.18 16:15:42