返回元素后如何正确关闭Selinium web驱动程序?

2024-10-06 14:20:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我有下面的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)



Tags: fromimportidbytimedriverseleniumelement
1条回答
网友
1楼 · 发布于 2024-10-06 14:20:44

当您打电话时:

first_availible = selenium_get_time(ort)

def selenium_get_time(ort)中,您正在调用:

finally:
    driver.close()
    driver.quit()

因此,当控件返回到main(ort)时,您将看到InvalidSessionIdException


解决方案

main(ort)ChromeDriver实例设置为global实例后,使用单独的方法关闭/退出WebDriverWeb浏览器,如下所示:

from selenium import webdriver

driver = None

def selenium_get_time(ort):
    global driver
    options = Options()
    options.headless = True
    driver = webdriver.Chrome(chrome_options=options, executable_path='/Users/andreas/.wdm/chromedriver/83.0.4103.39/mac64/chromedriver')
    .
    .
#This is the program that I run
def main(ort):
    first_availible = selenium_get_time(ort)
    .
    .
    tear_down()

def tear_down():
    driver.quit()

此外,请检查您正在使用的谷歌浏览器ChromeDriverSelenium二进制文件版本之间的兼容性

You can find a relevant discussion in selenium.common.exceptions.InvalidSessionIdException using GeckoDriver Selenium Firefox in headless mode through Python

相关问题 更多 >