0
这里的情况:关闭在子进程中打开的Selenium浏览器
我创建了一个子进程,它打开并处理webdriver。子进程是挑剔的,可能会出错,在这种情况下,它会立即关闭,控制权将返回到主函数。但是,在这种情况下,浏览器仍然会打开(因为子进程从未完全运行完毕)。如何关闭在子进程中初始化的浏览器?
途径到目前为止,我已经试过:
1)初始化在主函数中的webdriver并将它传递给子进程作为参数。
2)使用队列在子进程和父进程之间传递webdriver。
代码:
import multiprocessing
def foo(queue):
driver = webdriver.Chrome()
queue.put(driver)
# Do some other stuff
# If finicky stuff happens, this driver.close() will not run
driver.close()
if __name__ == '__main__':
queue = multiprocessing.Queue()
p = multiprocessing.Process(target=foo, name='foo', args=(queue,))
# Wait for process to finish
# Try to close the browser if still open
try:
driver = queue.get()
driver.close()
except:
pass
您可以使用driver.quit()方法关闭浏览器 – Piyush
不,这不会关闭浏览器。驱动程序在有时“挂起”的子进程中初始化。这意味着1)如果我将它放在foo()中,则不会总是达到driver.quit(),2)如果将驱动程序放在主函数中,driver.quit()将毫无意义,因为驱动程序是在独立处理。 –