'Selenium-Python: How to return webdriver from one function and pass into another function
I have two functions using selenium webdriver. One logs in, and another that performs authenticated actions on the website.
from selenium import webdriver
def login(driver):
driver.get('website.com')
# login
return driver
def do_stuff(driver):
driver.get('website.com/things')
# do stuff
return driver
if __name__ == '__main__':
driver = webdriver.Firefox()
driver = login(driver)
driver = do_stuff(driver)
driver.close()
The first function successfully logs in, but when the second function runs, I get the following error:
selenium.common.exceptions.InvalidSessionIdException: Message: Tried to run command without establishing a connection
I checked the session_id of the driver at the end of the first function and at the beginning of the first function, and they are the same. Also, it should not be an issue with the specific commands in the script, because it works when not split into two functions. I can provide a more specific code sample if it helps.
What am I missing, is there a way to get this to work?
Solution 1:[1]
I took your code and made a couple of simple tweaks to adjust with my environment, added print() statement and executed your program and seems it runs perfecto.
selenium4 based code
Code Block:
from selenium import webdriver
from selenium.webdriver.firefox.service import Service
def login(driver):
driver.get('https://www.selenium.dev/')
print("Within login")
return driver
def do_stuff(driver):
driver.get('https://www.selenium.dev/documentation/')
print("Within do_stuff")
return driver
if __name__ == '__main__':
driver = webdriver.Firefox(service=Service('C:\\BrowserDrivers\\geckodriver.exe'))
driver = login(driver)
driver = do_stuff(driver)
driver.quit()
Console Output:
Within login
Within do_stuff
Update
If you are still facing the InvalidSessionIdException error you need to cross check the compatibility of the versions of the binaries you are using.
You can find a relevant detailed discussion in selenium.common.exceptions.InvalidSessionIdException using GeckoDriver Selenium Firefox in headless mode through Python
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
