Ever
Ever

Reputation: 1

"selenium.common.exceptions.InvalidSessionIdException: Message: invalid session id" when opening a website with selenium twice

I wrote some code that opens a website and clicks a button in incognito mode. I wanted to make a loop but for some reason after opening the website second time it just crashes.

Error:

selenium.common.exceptions.InvalidSessionIdException: Message: invalid session id

Also i'm using Python 3.11.4, PyAutoGUI 0.9.53

Here is the code:

from selenium import webdriver
import time
import pyautogui
import win32api, win32con

options = webdriver.ChromeOptions()
options.add_argument("--incognito")
capability = options.to_capabilities()
driver = webdriver.Chrome(desired_capabilities=capability)

driver.get("Url")
time.sleep(1)
driver.execute_script("window.scrollTo(0, 3000)")
win32api.SetCursorPos((834, 258))
time.sleep(0.1)
click()
driver.close()
time.sleep(0.5)

driver.get("Url")
time.sleep(1)
driver.execute_script("window.scrollTo(0, 3000)")
win32api.SetCursorPos((834, 258))
time.sleep(0.1)
click()
driver.close()
time.sleep(0.5)

I didn't know what to do cuz im kind of new in programming so i just headed right here

Upvotes: 0

Views: 455

Answers (1)

vizallati
vizallati

Reputation: 7

You are closing the driver instance with driver.close() and still trying to use it in driver.get('Url'). You need to re-initiate the driver instance. Don't know why you chose to do it this way but, this should work

import time
import pyautogui
import win32api, win32con

options = webdriver.ChromeOptions()
options.add_argument("--incognito")
capability = options.to_capabilities()
driver = webdriver.Chrome(desired_capabilities=capability)

driver.get("Url")
time.sleep(1)
driver.execute_script("window.scrollTo(0, 3000)")
win32api.SetCursorPos((834, 258))
time.sleep(0.1)
click()
driver.close()
time.sleep(0.5)
driver = webdriver.Chrome(desired_capabilities=capability) #re-initialise 
driver.get("Url")
time.sleep(1)
driver.execute_script("window.scrollTo(0, 3000)")
win32api.SetCursorPos((834, 258))
time.sleep(0.1)
click()
driver.close()
time.sleep(0.5)

Upvotes: 0

Related Questions