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

从Python+Selenium转学JS时遇WebDriver会话错误求助

Fixing the 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 the geckodriver npm 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 19:12:49