简体   繁体   English

Python:Selenium中的异常处理

[英]Python : Exception handling in Selenium

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

I have the above code snippet. 我有上面的代码片段。 I want to try to call f1() and if it throws an error (which it does as dagsb.com doesnt exist) I want to call f2() 我想尝试调用f1() ,如果它抛出错误(由于dagsb.com不存在而发生了错误),我想调用f2()

How can I do so? 我该怎么办?

Use try and except to handle webdriver-specific errors : 使用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")

Note that this is not going to handle Page not found 404 - since in that case, there would not be an exception thrown. 请注意,这不会处理“找不到页面” 404,因为在这种情况下,不会引发异常。 The idea would be to check the page title not to equal "Page not found": 想法是检查页面标题不等于“找不到页面”:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM