selenium2-异常断言

来源:互联网 发布:shell编程简单题 编辑:程序博客网 时间:2024/06/03 16:17

                                                        Python 异常断言


    在实际脚本开发中,需要用到python的异常处理来捕获异常和抛出异常,所以需要学习python的异常处理。

>>>open(r'abc.text')

Traceback(most recent call last):

  File"<stdin>",line 1 in<module>

IOError:[Erron 2]No such file directory:'abc.txt'

打开一个不存在的文件ac.txt文件,当系统找不到时,就会抛出一个IOError类型错误。

(1)Try...except...

假如我们已经知道这个错误,就可以通过一个异常捕捉来捕捉这个错误,使用try..来接收这个错误。打开文件写入:

try:                               打印出具体信息错误内容:    try:

   open(r"abc.txt")                                                          open('abc.txt')

except IOError:                                                             exceptIOError,msg:

  pass                                                                              printmsg

(2)try...finally...
试用情况:我们不管捕捉到什么错误,无论错误是不是发生,这些代码必须运行,比如:关闭文件、释放锁、把数据库连接返还给连接池等。
import timetry:    f=file('pome.txt')    while True:# our usual file-reading idiom        line =f.readline()        if len(line)==0:            break        time.sleep(2)        print line,finally:    f.close()    print 'Cleaning up...closed the file'
读取pome.txt文件中的每一行,在执行中使用ctrl+c终止程序,但是文件仍然会被关闭。
二:抛出异常
(1)Raise抛出异常
#coding=utf-8filename=raw_input('please input file name:')if filename=='hello':   raise NameError('input file name error!')
程序要求用户输入一个文件名,如果用户输入的文件名是hello ,那么抛出一个NameError 的异常,用户输入hello 和NameError 异常之间没有任何必然联系,我只是人为的通过raise 来这样定义,我当然也可以定义称TypeError ,但我定义的异常类型必须是python 提供的。

三:错误页面的截图

driver=webdriver.Firefox()driver.get('https://www.baidu.com')try:  driver.find_element_by_id("kwsss").send_keys('3ee')  driver.find_element_by_id("su").click()except:  driver.get_screenshot_as_file("E:/tools/2.jpg")

原创粉丝点击