python : Exception handling in Selenium

标签 python selenium

from selenium import webdriver
w1=webdriver.Firefox()
def f1():
    w1.get("dagsb.com")
def f2():
    w1.get("google.com")

我有上面的代码片段。我想尝试调用 f1() ,如果它抛出错误(因为 dagsb.com 不存在),我想调用 f2()

我该怎么做?

最佳答案

使用try except来处理特定于webdriver的错误:

from selenium.common.exceptions import WebDriverException

try:
    w1.get("http://dagsb.com")
except WebDriverException as e:
    # TODO: log exception
    w1.get("https://google.com")

请注意,这不会处理找不到页面 404 - 因为在这种情况下,不会抛出异常。这个想法是检查页面标题不等于“找不到页面”:

is_found = w1.title != page_not_found_message
if not is_found:
    w1.get("https://google.com")

关于 python : Exception handling in Selenium,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35066215/

相关文章:

python - 在对象的 __class__ 属性上设置属性

python - Python和Haskell有C/C++的 float 不确定性问题吗?

python - Pygame 运行缓慢

selenium - 如何使用 PhantomJS 在 Geb/Selenium 中设置 cookie

java - Selenium 2 WebDriver 使用自定义配置文件

python - 如何找到以某种方式更改字符串的递归函数的基本情况

python - 上采样数据和插值

python - Selenium Python : 'ElementNotInteractableException'

java - 在另一台计算机上运行 Java/Selenium 程序

java - 等待在 Firefox 浏览器中无法工作 (Webdriver selenium 2.0 +Java)