無效的會話 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

另見