I have the following selenium script the waits for the page to load and looks for an element. After the element is retrieved I want to close the driver s that my ram gets freed up, but instead the whole ends in a InvalidSessionIdException
meaning the driver is closed at an inappropriate time. How do I properly close my driver after getting the information that I want?
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
def selenium_get_time(ort):
options = Options()
options.headless = True
driver = webdriver.Chrome(chrome_options=options, executable_path='/Users/andreas/.wdm/chromedriver/83.0.4103.39/mac64/chromedriver')
driver.get("https://fp.trafikverket.se/boka/#/search/dIccADaISRCIi/5/0/0/0")
element = WebDriverWait(driver, 40).until(EC.element_to_be_clickable((By.CLASS_NAME, "form-control")))
driver.find_element_by_xpath("//select[@id='examination-type-select']/option[@value='3']").click()
driver.find_element_by_xpath("//select[@id='language-select']/option[@value='13']").click()
driver.find_element_by_id('id-control-searchText').clear()
inputElement = driver.find_element_by_id("id-control-searchText")
inputElement.send_keys(ort)
inputElement.send_keys(Keys.ENTER)
# time.sleep(10)
try:
element = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, "//div[@class='col-sm-3 text-center']/button[@data-bind='click:$parent.select']")))
first_time = driver.find_element_by_xpath("//div[@class='col-xs-6']/strong")
return first_time.text
except (NoSuchElementException, TimeoutException) as e:
if NoSuchElementException:
print('Nothing found for: ', ort, ' NoElemFound')
else:
print('Nothing found for: ', ort, ' TimedOut')
finally;
driver.close()
driver.quit()
#This is the program that I run
def main(ort):
first_availible = selenium_get_time(ort)
if first_availible:
date = convert_time(first_availible)
if check_schedule(date, '2020-07-01', '2020-07-05'):
print('FOUND: ', ort +' '+ first_availible)
send_email(first_availible, ort)
else:
now = datetime.datetime.now()
dt_string = now.strftime("%H:%M:%S")
print('Found Nothing for: ', ort, ' ', dt_string)