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

os.system与driver.get()结合时Selenium无法启动Chrome的问题

问题分析与解决方案

问题根源

你遇到的问题和os.system()的特性直接相关:os.system()是阻塞式调用,它会等待启动的AppABC.exe进程完全退出后,才会继续执行后续的Selenium代码。但AppABC.exe是持续运行的服务程序,所以你的代码会一直卡在Step1,根本没有执行到Step2的Chrome启动逻辑。而手动启动AppABC时,它独立于Python脚本运行,脚本无需等待其退出,因此能正常执行后续步骤。

解决方案

用非阻塞的进程启动方式替代os.system(),推荐使用Python标准库的subprocess.Popen,它启动外部程序后不会阻塞当前脚本的执行流程。

修改后的Step1代码如下:

import subprocess

# Step 1: 非阻塞启动AppABC
vr_StartApp = subprocess.Popen(r'"C:/Program Files (x86)/ABC/AppABC/AppABC.exe"')

额外建议:

  • 可以添加短暂的延迟(比如time.sleep(2)),确保AppABC服务完全启动后再执行Selenium的访问逻辑,避免因服务未就绪导致的访问失败。
  • 如果需要检查AppABC是否成功启动,可以通过vr_StartApp.poll()方法获取进程状态,返回None表示进程仍在运行。

完整修改后的代码示例

#-- IMPORT LIBRARY:
import time
import subprocess
import unittest
from selenium import webdriver
from selenium.webdriver.common.by import By


class TC_01_Start9222(unittest.TestCase):
    
    def setUp(self):
        #Step 1: 非阻塞启动AppABC
        vr_StartApp = subprocess.Popen(r'"C:/Program Files (x86)/ABC/AppABC/AppABC.exe"')
        # 等待服务就绪
        time.sleep(2)
                
        #Step 2:
        self.Driver = webdriver.Chrome()
        self.Driver.get("http://localhost:9222")
        print(self.Driver.title)
        vr_AppABC_GUI = self.Driver.find_element(By.XPATH, "//*[@id='items']/a[1]")
        vr_AppABC_GUI.click()

    def test_MainTC(self):
        pass
    
    def tearDown(self):       
        time.sleep(100)
        self.Driver.quit()


#-- REPORT BY UNITTEST-------------# 
if __name__ == "__main__":
    unittest.main()
#----------------------------------#

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 09:05:21