2017-08-14 61 views
2

后,我完成运行以下Python代码:正确端接硒浏览器在Python

在我 Linux
from selenium.webdriver import Firefox 
from contextlib import closing 

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

目前还有听geckodriver过程。

$ 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               

如何调整Python代码,以便它也终止进程?

回答

1

这是因为在硒的情况下,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")