2

當我的硒程序由於某種錯誤而崩潰時,它似乎留下正在運行的進程。硒離開正在運行的進程?

例如,這裏是我的進程列表:

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() 

有時,瀏覽器不會加載網頁元素的速度不夠快,從而硒崩潰時,嘗試點擊它沒有找到的東西。其他時候它工作正常。

這是一個簡單的例子,爲了簡單起見,但有了更復雜的硒程序,什麼是保證乾淨的退出方式,而不是留下正在運行的進程?它應該在意外崩潰和成功運行時乾淨地退出。

回答

0

發生什麼事是你的代碼拋出一個異常,停止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語句中使用,但它很難推薦一個無需更好了解你的代碼庫。

2

Chromedriver.exe每次Selenium在Chrome上運行時都會擠佔TaskManager(在Windows的情況下)。有時,即使瀏覽器沒有崩潰,它也不會清除。

我通常運行bat文件或cmd殺死所有現有的chromedriver.exe進程,然後再啓動另一個進程。

看看這個:release Selenium chromedriver.exe from memory

  • 我知道這是一個Unix相關的問題,但我相信它在Windows處理方式,可以在那裏使用。
+1

考慮到示例過程輸出,該問題似乎與* nix相關。 –