当我的Selenium程序由于某些错误而崩溃时,它似乎留着正在运行的进程。
例如,这是我的流程列表:
carol 30186 0.0 0.0 103576 7196 pts/11 Sl 00:45 0:00 /home/carol/test/chromedriver --port=51789
carol 30322 0.0 0.0 102552 7160 pts/11 Sl 00:45 0:00 /home/carol/test/chromedriver --port=33409
carol 30543 0.0 0.0 102552 7104 pts/11 Sl 00:48 0:00 /home/carol/test/chromedriver --port=42567
carol 30698 0.0 0.0 102552 7236 pts/11 Sl 00:50 0:00 /home/carol/test/chromedriver --port=46590
carol 30938 0.0 0.0 102552 7496 pts/11 Sl 00:55 0:00 /home/carol/test/chromedriver --port=51930
carol 31546 0.0 0.0 102552 7376 pts/11 Sl 01:16 0:00 /home/carol/test/chromedriver --port=53077
carol 31549 0.5 0.0 0 0 pts/11 Z 01:16 0:03 [chrome] <defunct>
carol 31738 0.0 0.0 102552 7388 pts/11 Sl 01:17 0:00 /home/carol/test/chromedriver --port=55414
carol 31741 0.3 0.0 0 0 pts/11 Z 01:17 0:02 [chrome] <defunct>
carol 31903 0.0 0.0 102552 7368 pts/11 Sl 01:19 0:00 /home/carol/test/chromedriver --port=54205
carol 31906 0.6 0.0 0 0 pts/11 Z 01:19 0:03 [chrome] <defunct>
carol 32083 0.0 0.0 102552 7292 pts/11 Sl 01:20 0:00 /home/carol/test/chromedriver --port=39083
carol 32440 0.0 0.0 102552 7412 pts/11 Sl 01:24 0:00 /home/carol/test/chromedriver --port=34326
carol 32443 1.7 0.0 0 0 pts/11 Z 01:24 0:03 [chrome] <defunct>
carol 32691 0.1 0.0 102552 7360 pts/11 Sl 01:26 0:00 /home/carol/test/chromedriver --port=36369
carol 32695 2.8 0.0 0 0 pts/11 Z 01:26 0:02 [chrome] <defunct>
这是我的代码:
from selenium import webdriver
browser = webdriver.Chrome("path/to/chromedriver")
browser.get("http://stackoverflow.com")
browser.find_element_by_id('...').click()
browser.close()
有时,浏览器无法足够快地加载网页元素,因此Selenium在尝试单击未找到的内容时会崩溃。其他时候它工作正常。
为了简单起见,这是一个简单的示例,但是对于更复杂的Selenium程序,退出和不退出正在运行的进程的保证的干净方法是什么?它应该在意外崩溃和成功运行时干净地退出。
发生的事情是您的代码引发了异常,导致python进程无法继续进行。这样,就不会在浏览器对象上调用close / quit方法,因此chromedrivers无限期地闲逛。
您需要使用try / except块来确保每次都调用close方法,即使抛出异常也是如此。一个非常简单的示例是:
from selenium import webdriver
browser = webdriver.Chrome("path/to/chromedriver")
try:
browser.get("http://stackoverflow.com")
browser.find_element_by_id('...').click()
except:
browser.close()
browser.quit() # I exclusively use quit
您可以在此处采用许多更为复杂的方法,例如创建一个与该with
语句一起使用的上下文管理器,但是如果不更好地了解您的代码库,很难推荐一种方法。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句