無效的會話 ID

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

另請參見