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

使用unittest模块时WebDriver未启动浏览器问题求助

Hey Robert, let's break down why your browser isn't launching when using the unittest class structure—this is a common gotcha with Python's unittest framework!

The Core Issues

Your code is missing two critical pieces that make unittest run your test logic:

  1. No test_ prefixed methods: Unittest only automatically executes methods whose names start with test_. Without these, the framework doesn't see any test cases to run, so it exits immediately with code 0 (no errors, but no work done either).
  2. No test runner entry point: You need to explicitly tell Python to kick off the unittest test runner when your script runs.

Fixed Code Example

Here's the adjusted version of your code with these fixes, plus some best practices:

import unittest
from selenium import webdriver

class GlossaryPage(unittest.TestCase):
    def setUp(self):
        # Use a raw string for the path to avoid escape character issues
        self.driver = webdriver.Chrome(r'D:\chromedriver\chromedriver.exe')
        self.driver.get("site URL")

    # This method will run because it starts with test_
    def test_page_title(self):
        # Add your actual test logic here (example checks page title)
        self.assertIn("Your Expected Page Title", self.driver.title)
        print("Test ran successfully—browser launched!")

    def tearDown(self):
        # Clean up: closes the browser after each test
        self.driver.quit()

# Entry point to trigger the unittest runner
if __name__ == '__main__':
    unittest.main()

Key Explanations

  • test_ method naming: Any method you want unittest to execute must start with test_ (like test_page_title above). This is how the framework identifies test cases.
  • Test runner entry: The if __name__ == '__main__': unittest.main() line tells Python to launch the unittest test runner when you run the script directly, which triggers the setUp, test method, and tearDown flow.
  • Raw string for paths: Using r'' around your ChromeDriver path prevents Python from interpreting backslashes as escape characters (a common source of silent failures).
  • tearDown method: This runs automatically after each test to clean up resources (like closing the browser) and avoids leftover browser processes.

Quick Check

If it still doesn't work, double-check that your ChromeDriver version matches your installed Chrome browser version—mismatches can cause silent launch failures (though your non-class code works, so this is probably not the issue here).

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 04:25:47