xralf
xralf

Reputation: 3632

Properly terminate the selenium browser in Python

After I finish running the following Python code:

from selenium.webdriver import Firefox
from contextlib import closing

with closing(Firefox()) as browser:
  # some code here

There are still listening geckodriver processes in my Linux machine.

$ ss -arp
LISTEN      0      128                                                    localhost:44132                                                           *:*        users:(("geckodriver",21698,3))
LISTEN      0      128                                                    localhost:57893                                                           *:*        users:(("geckodriver",20242,3))
LISTEN      0      128                                                    localhost:34439                                                           *:*        users:(("geckodriver",19440,3))
LISTEN      0      128                                                    localhost:35435                                                         

How to adjust the Python code, so that it will terminate the processes as well?

Upvotes: 2

Views: 651

Answers (1)

Tarun Lalwani
Tarun Lalwani

Reputation: 146510

That is because in case of selenium close method closes the current window/browser but not exit it. You need to use quit method. So your code should be

from selenium.webdriver import Firefox
from contextlib import contextmanager

@contextmanager
def quiting(thing):
    try:
        yield thing
    finally:
        thing.quit()

with quiting(Firefox()) as browser:
    browser.get("http://sample.com")

Upvotes: 1

Related Questions