2014-12-22 185 views
2

所以我想抓住Webdriver异常,不希望它的回溯污染我的日志。下面是代码不能捕捉到异常

from selenium.common.exceptions import TimeoutException, WebDriverException 

try: 
    WebDriverWait(driver, 10).until(
     EC.presence_of_element_located((By.CSS_SELECTOR, '.loading'))) 
except TimeoutException: 
    log.msg("Seneium Timeout: {}".format(response.url)) 
except WebDriverException as e: 
    log.msg("Selenium Exception: {0} Message: {1}".format("my message", str(e))) 
finally: 
    driver.quit() 

尚未到位,我还是让这些:

<full traceback here> 
selenium.common.exceptions.WebDriverException: Message: Can not connect to GhostDriver 

我在做什么错?

+1

你确定在'try'块中发生异常吗? –

回答

5

的异常引发外界您try/except块的同时初始化WebDriver实例:

driver = webdriver.PhantomJS() 

仅供参考,出现这种情况,同时与GhostDriversource code开始PhantomJS,报价:

def start(self): 
    """ 
    Starts PhantomJS with GhostDriver. 

    :Exceptions: 
    - WebDriverException : Raised either when it can't start the service 
     or when it can't connect to the service 
    """ 
    try: 
     self.process = subprocess.Popen(self.service_args, stdin=subprocess.PIPE, 
             close_fds=platform.system() != 'Windows', 
             stdout=self._log, stderr=self._log) 

    except Exception as e: 
     raise WebDriverException("Unable to start phantomjs with ghostdriver.", e) 
    count = 0 
    while not utils.is_connectable(self.port): 
     count += 1 
     time.sleep(1) 
     if count == 30: 
      raise WebDriverException("Can not connect to GhostDriver") 

而且,start()called in WebDriver's constructor (__init__() method)

换句话说,它启动服务,但无法连接到它。

+0

最有可能driver.get(url),但你是对的。谢谢。 – yayu

+1

@yayu更新了与源代码链接的答案。它发生在webdriver的初始化步骤上。感谢您激励我寻找来源:) – alecxe

+0

你是这里的灵感:) – yayu