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()將毫無意義,因爲驅動程序是在獨立處理。 –