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/