简体   繁体   中英

Python3, Selenium, Chromedriver console window

I've a made a selenium test using python3 and selenium library.

I've also used Tkinter to make a GUI to put some input on (account, password..).

I've managed to hide the console window for python by saving to the .pyw extension; and when I make an executable with my code, the console doesn't show up even if it's saved with .py extension.

However, everytime the chromedriver starts, it also starts a console window, and when the driver exists, this window does not.

so in a loop, i'm left with many webdriver consoles.

Is there a work around this to prevent the driver from launching a console everytime it runs ?

I hated dealing with this in selenium until I remembered that this was an obvious use case for context managers just like the usage of open .

I did find out that selenium is about to add this officially to their package in this pull request

Until this is officially added, this snippet should give you the functionality you need to get things going :)

import contextlib

@contextlib.contextmanager
def Chrome(*args, **kwargs):
    webdriver = webdriver.Chrome(*args, **kwargs)
    try:
        yield webdriver
    finally:
        webdriver.quit()

with Chrome() as driver:
    # whatever you're planning on doing goes here

driver.close() and driver.quit() are two different methods for closing the browser session in Selenium WebDriver.

driver.close() - It closes the the browser window on which the focus is set.

driver.quit() – It basically calls driver.dispose method which in turn closes all the browser windows and ends the WebDriver session gracefully.

You should use driver.quit whenever you want to end the program. It will close all opened browser window and terminates the WebDriver session. If you do not use driver.quit at the end of program, WebDriver session will not close properly and files would not be cleared off memory. This may result in memory leak errors.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM