I'm trying to close the browser then reopen it without getting any errors.
I tried doing driver.close()
then webdriver.Chrome(executable_path=driver_path, options=option)
to reopen it, but it brings up selenium.common.exceptions.InvalidSessionIdException: Message: invalid session id
If you're wondering why I want to do this, I'm tyring to clear all cache and cookies. I thought maybe delete_all_cookies
might work but it doesn't.
You should be able to recreative everything with this:
import json
from selenium import webdriver
from contextlib import suppress
# \/\/ Webdriver & browser stuff \/\/
driver_path = ''
chrome_path = ''
option = webdriver.ChromeOptions()
option.binary_location = chrome_path
# option.add_argument("--headless")
option.add_argument("--disable-gpu")
option.add_experimental_option("excludeSwitches", ["enable-logging"])
with suppress(Exception): # Load prefrences file
with open('drivers/Preferences') as jsonFile:
pref = json.load(jsonFile)
option.add_experimental_option("prefs", pref)
driver = webdriver.Chrome(executable_path=driver_path, options=option)
# /\/\ Webdriver & browser stuff /\/\
# THE MAIN PORTION \/\/
driver.get("https://example.com/")
driver.close()
webdriver.Chrome(executable_path=driver_path, options=option) # this reopens it
driver.get("https://example.org")
# An error should come up after the above.
This is the error:
File "g:\pbl\question.py", line 24, in <module>
driver.get("https://example.org")
File "C:\Users\antho\AppData\Roaming\Python\Python310\site-packages\selenium\webdriver\remote\webdriver.py", line 333, in get
self.execute(Command.GET, {'url': url})
File "C:\Users\antho\AppData\Roaming\Python\Python310\site-packages\selenium\webdriver\remote\webdriver.py", line 321, in execute
self.error_handler.check_response(response)
File "C:\Users\antho\AppData\Roaming\Python\Python310\site-packages\selenium\webdriver\remote\errorhandler.py", line 242, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.InvalidSessionIdException: Message: invalid session id
CodePudding user response:
You did not assign a new webdriver instance to driver
variable. It still reference the old closed instance.
Do
driver = webdriver.Chrome(executable_path=driver_path, options=option)
again.