我有下面的selenium脚本,它等待页面加载并查找元素。在元素被检索之后,我想关闭驱动程序,这样我的ram就被释放了,但是整个过程以InvalidSessionIdException
结束,这意味着驱动程序在不合适的时间被关闭。在获得所需信息后,如何正确关闭驱动程序
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)
当您打电话时:
在
def selenium_get_time(ort)
中,您正在调用:因此,当控件返回到
main(ort)
时,您将看到InvalidSessionIdException
解决方案
在
main(ort)
将ChromeDriver实例设置为global
实例后,使用单独的方法关闭/退出WebDriver和Web浏览器,如下所示:此外,请检查您正在使用的谷歌浏览器,ChromeDriver,Selenium二进制文件版本之间的兼容性
相关问题 更多 >
编程相关推荐