无效的会话 ID

无效会话 ID(invalid session ID)错误是一种 WebDriver 错误,当服务器无法识别唯一的会话标识符时会发生。这通常发生在 会话已被删除 或会话 ID 无效的情况下。

示例

显式会话删除

当退出时,WebDriver 会话会被显式删除

python
from selenium import webdriver
from selenium.common import exceptions

session = webdriver.Firefox()
print("Current session is {}".format(session.session_id))
session.quit()

try:
    session.get("https://mozilla.org")
except exceptions.InvalidSessionIdException as e:
    print(e.message)

输出

Current session is 46197c16-8373-469b-bc56-4c4d9e4132b4
No active session with ID 46197c16-8373-469b-bc56-4c4d9e4132b4

隐式会话删除

如果关闭最后一个窗口或标签页,会话也可能被隐式删除

python
from selenium import webdriver
from selenium.common import exceptions

session = webdriver.Firefox()
print("Current session is {}".format(session.session_id))

# closes current window/tab
session.close()

try:
    session.get("https://mozilla.org")
except exceptions.InvalidSessionIdException as e:
    print(e.message)

输出

Current session is 46197c16-8373-469b-bc56-4c4d9e4132b4
No active session with ID 46197c16-8373-469b-bc56-4c4d9e4132b4

另见