2016-09-21 55 views
2

我正在使用selenium + python,一直在使用隱式等待並嘗試/在python上的代碼以捕獲錯誤。但是我一直注意到,如果瀏覽器崩潰(假設用戶在程序執行期間關閉瀏覽器),我的python程序將掛起,並且在發生這種情況時,隱式等待的超時似乎不起作用。下面的過程將永遠停留在那裏。如果Web瀏覽器在硒中崩潰,進程掛起

from selenium.webdriver.support import expected_conditions as EC 
from selenium.webdriver.support.ui import WebDriverWait 
from selenium.webdriver.common.keys import Keys 
from selenium.webdriver.common.by import By 
from selenium import webdriver 
import datetime 
import time 
import sys 
import os 

def open_browser(): 
    print "Opening web page..." 

    driver = webdriver.Chrome() 

    driver.implicitly_wait(1) 
    #driver.set_page_load_timeout(30) 
    return driver 


driver = open_browser() # Opens web browser 

# LET'S SAY I CLOSE THE BROWSER RIGHT HERE! 
# IF I CLOSE THE PROCESS HERE, THE PROGRAM WILL HANG FOREVER 
time.sleep(5) 
while True: 
    try: 
     driver.get('http://www.google.com') 
     break 
    except: 
     driver.quit() 
     driver = open_browser() 
+0

好像這是一個錯誤,當一個套接字連接關閉析構函數應該會終止驅動程序。 –

回答

0

您提供的代碼將永遠掛起,如果有一個例外獲取谷歌主頁。 可能發生的事情是,試圖獲取谷歌主頁導致了一個異常,通常會暫停程序,但你用except子句掩蓋了這一點。

嘗試對您的循環進行以下修改。

max_attemtps = 10 
attempts = 0 
while attempts <= max_attempts: 
    try: 
     print "Retrieving google" 
     driver.get('http://www.google.com') 
     break 
    except: 
     print "Retrieving google failed" 
     attempts += 1 
+0

這是事情。該代碼被掛在「嘗試」部分,但它從來沒有達到除了。所以這意味着不會拋出異常,但是當瀏覽器因爲某個原因而關閉時,並且selenium查找元素或嘗試打開頁面時,不會引發異常並且代碼會掛起。我編輯了關於除了部分之外的代碼,它從來沒有達到過。 –