如何使用Selenium和Python在测试执行后关闭Headless Firefox

3

我一直在关注这个教程来学习如何使用Selenium。我刚刚成功地运行了以下代码:

from selenium.webdriver import Firefox
from selenium.webdriver.firefox.options import Options

opts = Options()opts.headless=True
assert opts.headless # Operating in headless mode
browser = Firefox(options=opts)browser.get('https://bandcamp.com')
browser.find_element_by_class('playbutton').click()

如何确保无头Firefox不再运行?我运行了这段代码两次,现在两首歌曲同时播放。任何帮助都将不胜感激,我只想确保没有后台进程正在运行!

4个回答

2
无论是基于GUI的浏览器还是浏览器,在测试执行结束时,您都应该调用browser.quit(),它会调用/shutdown endpoint,随后WebDriver实例和浏览上下文都会被完全销毁,关闭所有页面/选项卡/窗口。

因此,您的有效代码块将是:

# previous lines of code
browser.find_element_by_class('playbutton').click()
browser.quit()

您可以在PhantomJS Web Driver保留在内存中中找到详细的讨论。
然而,在极少数情况下可能会出现WebDriver的残留实例,例如ChromeDriver占用内存,在这些情况下,您需要使用强制方法将它们关闭,然后才能触发下一个测试执行,方法如下:
  • Python Solution (Windows):

    import os
    
    os.system("taskkill /f /im geckodriver.exe /T")
    os.system("taskkill /f /im chromedriver.exe /T")
    os.system("taskkill /f /im IEDriverServer.exe /T")
    
  • Python Solution (Cross Platform):

    import os
    import psutil
    
    PROCNAME = "geckodriver" # or chromedriver or IEDriverServer
    for proc in psutil.process_iter():
        # check whether the process name matches
        if proc.name() == PROCNAME:
        proc.kill()
    
您可以在Selenium:如何停止geckodriver进程影响PC内存,而不调用driver.quit()?中找到详细讨论。

0

你可以添加browser.close()以关闭当前标签页,添加browser.quit()以关闭所有浏览器窗口并结束驱动程序的会话/进程。


0
从您分享的教程中:
一切似乎都在正常工作。为了防止无形的无头浏览器实例在您的计算机上堆积,您需要在退出Python会话之前关闭浏览器对象:
尝试执行以下操作,看看是否解决了您的问题:
browser.close()
quit()

编辑:

让我们搞清楚这件事。根据您的要求,我们目前有:

from selenium.webdriver import Firefox
from selenium.webdriver.firefox.options import Options
from selenium import webdriver # you need this to terminate program 

options = Options() 
options.headless = True

driver = webdriver.Firefox(options=options)

driver.get('https://bandcamp.com')

driver.find_element_by_class('playbutton').click()

ch = input('Do you want to quit the program y/n?')
if ch == 'y':
    driver.quit()
    print('The program is terminated')

如果解决方案无效,请告诉我。

谢谢!很抱歉,我应该提到我尝试在程序结尾添加那个,但无济于事 - Firefox 仍然打开/运行。 - Christina
在这种情况下,您需要“驱动程序”来终止程序。我会相应地进行编辑。@Christina - liamsuma
@Christina 如果还是不行,请让我知道已经编辑过了。 - liamsuma

0

只需添加

browser.close()

另外,您可以查看进程列表(例如,在Ubuntu中使用lsof命令)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接