从Python+Selenium转学JS时遇WebDriver会话错误求助
NoSuchSessionError When Calling driver.quit() in Selenium JavaScript Hey there! I’ve run into this exact hiccup when switching from Python Selenium to the JS version—async operations are the main culprit here. Let’s break down what’s going on and how to fix it:
The Root Cause
Selenium’s JavaScript API is promise-based, meaning methods like build(), get(), and quit() don’t run synchronously. In your original code, driver.quit() might be executing before the driver finishes initializing or the page finishes loading. This leads to the "no session exists" error because the connection was never properly established (or got dropped prematurely).
Solution 1: Use async/await to Manage Asynchronous Flow
Wrap your code in an async function and use await for every Selenium operation to ensure they run in the correct order. Here’s your updated, working code:
const { Builder, By, until } = require('selenium-webdriver'); async function runFirefoxTest() { let driver; try { // Wait for the driver to finish initializing driver = await new Builder() .forBrowser('firefox') .build(); // Wait for the page to fully load await driver.get('http://google.com'); // Optional: Add a wait to confirm the page loaded (e.g., check the title) await driver.wait(until.titleContains('Google'), 5000); } finally { // Only quit if the driver was successfully created if (driver) { await driver.quit(); } } } // Run the test and catch any errors runFirefoxTest().catch(err => console.error('Test failed:', err));
Solution 2: Double-Check GeckoDriver Setup
Since you’re using Firefox, make sure:
- GeckoDriver is installed and added to your system’s
PATH(you can also use thegeckodrivernpm package to manage it automatically) - You’re using a GeckoDriver version compatible with your Firefox browser
If GeckoDriver isn’t detected properly, the driver session might terminate unexpectedly before you call quit().
Key Difference from Python Selenium
Unlike Python’s Selenium (which uses a synchronous API by default), the JS version relies entirely on promises. Skipping await creates race conditions where operations don’t complete in the order you expect—this is why removing driver.quit() "fixes" the error (it just stops the code from trying to quit a session that never fully started).
内容的提问来源于stack exchange,提问作者BigEfromDaBX

