Python:Selenium中的异常处理

2024-04-18 23:55:07 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

我怎么能这么做?你知道吗


Tags: 代码fromimportcomgetdefselenium错误
1条回答
网友
1楼 · 发布于 2024-04-18 23:55:07

使用tryexcept来处理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")

请注意,这不会处理PageNotFound404,因为在这种情况下,不会引发异常。其想法是检查页面标题是否等于“未找到页面”:

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

相关问题 更多 >