【问题标题】:Not being able to catch an exception无法捕获异常
【发布时间】:2014-12-22 02:53:24
【问题描述】:

所以我试图捕捉 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

我做错了什么?

【问题讨论】:

  • 您确定异常发生在try 块内吗?

标签: python exception selenium selenium-webdriver


【解决方案1】:

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

driver = webdriver.PhantomJS()

仅供参考,这发生在以GhostDriver 开头的PhantomJS 时,引用source code

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)

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

【讨论】:

  • 很可能是在 driver.get(url) 但你是对的。谢谢。
  • @yayu 使用源代码链接更新了答案。它发生在 webdriver 的初始化步骤中。感谢您激励我寻找资源:)
  • 你是这里的灵感来源 :)
【解决方案2】:

你可以试试 - ElementClickInterceptedException

【讨论】:

    猜你喜欢
    • 2010-10-29
    • 2021-10-09
    • 2021-09-17
    • 2021-10-03
    • 2018-02-04
    • 2018-02-04
    • 2011-04-19
    • 2017-08-10
    相关资源
    最近更新 更多