简体   繁体   English

关闭在子进程中打开的Selenium浏览器

[英]Closing Selenium Browser that was Opened in a Child Process

Here's the situation: 情况如下:

I create a child process which opens and deals with a webdriver. 我创建一个子进程,该子进程将打开并处理Webdriver。 The child process is finicky and might error, in which case it would close immediately, and control would be returned to the main function. 子进程是挑剔的,可能会出错,在这种情况下它将立即关闭,并将控制权返回给主函数。 In this situation, however, the browser would still be open (as the child process never completely finished running). 但是,在这种情况下,浏览器仍将处于打开状态(因为子进程从未完全完成运行)。 How can I close a browser that is initialized in a child process? 如何关闭在子进程中初始化的浏览器?

Approaches I've tried so far: 到目前为止我尝试过的方法:

1) Initializing the webdriver in the main function and passing it to the child process as an argument. 1)在主函数中初始化webdriver,并将其作为参数传递给子进程。

2) Passing the webdriver between the child and parent process using a queue. 2)使用队列在子进程和父进程之间传递webdriver。

The code: 编码:

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

I found a solution: 我找到了解决方案:

In foo(), get the process ID of the webdriver when you open a new browser. 在foo()中,打开新的浏览器时获取Webdriver的进程ID。 Add the process ID to the queue. 将进程ID添加到队列中。 Then in the main function, add time.sleep(60) to wait for a minute, then get the process ID from the queue and use a try-except to try and close the particular process ID. 然后在主函数中,添加time.sleep(60)等待一分钟,然后从队列中获取进程ID,并使用try-except尝试关闭特定的进程ID。

If foo() running in a separate process hangs, then the browser will be closed in the main function after one minute. 如果在单独进程中运行的foo()挂起,则一分钟后,浏览器将在主函数中关闭。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM