运行以下from selenium.webdriver import Firefox
from contextlib import closing
with closing(Firefox()) as browser:
# some code here
代码后
Linux
我的$ 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
计算机中仍然有监听geckodriver进程。
Python
如何调整{{1}}代码,以便它也会终止进程?
答案 0 :(得分:1)
这是因为在selenium close
方法的情况下关闭当前窗口/浏览器但不退出它。您需要使用quit
方法。所以你的代码应该是
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")