Python 无法捕获异常

Python 无法捕获异常,python,exception,selenium,selenium-webdriver,Python,Exception,Selenium,Selenium Webdriver,因此,我试图捕获Webdriver异常,不希望其回溯污染我的日志。下面是一段代码 from selenium.common.exceptions import TimeoutException, WebDriverException try: WebDriverWait(driver, 10).until( EC.presence_of_element_located((By.CSS_SELECTOR, '.loading'))) except TimeoutExcep

因此,我试图捕获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

selenium.common.exceptions.WebDriverException:消息:无法连接到GhostDriver

我做错了什么?

初始化
WebDriver
实例时,在
try/except
块之外引发异常:

driver = webdriver.PhantomJS()

仅供参考,这是在使用GhostDriver启动PhantomJS时发生的,引用自:

并且,
start()


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

您可以尝试-元素ClickInterceptedException

您确定异常发生在
try
块中吗?很可能是在driver.get(url)时,但您是对的。谢谢。@yayu用源代码链接更新了答案。它发生在webdriver的初始化步骤上。谢谢你激励我去寻找资料:)你是这里的灵感:)
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")