zoukankan      html  css  js  c++  java
  • 自动化测试(四):VBScript脚本语言

             VBS基于对象,只能利用现成的对象,不能封装、继承等,意味着不是真正的面向对象

    语言的学习:

             1.数据定义,变量定义,表达式

             2.程序控制结构

             3.函数,方法,类

             4.异常处理

    VBScript的数据类型

             VBScript只用一种数据类型,称为Variant,Variant是一种特殊的数据类型,根据使用的方式,它可以包含不同类别的信息,因为Variant是VBS中唯一的数据类型,所以它也是VBS中所有函数的返回值的数据类型,包括Empty,Null和Error三种特殊类型。

             最简单的Variant可以包含数字或字符串信息,Variant用于数字上下文中时作为数字处理,用于字符串上下文中时作为字符串处理,这就是说,如果看起来像是数字的数据,则VBS会假定其为数字并以使用于数字的方式处理,与此类似,如果使用的数据只可能是字符串,则VBS将按字符串处理,也可以将数字包含在引号(“”)中使其成为字符串。

    Variant数据子类型

             Empty:未初始化的Variant,对于数值变量,值为0,;对于字符串变量,值为零长度字符串(“”)

             Null:不包含任何有效数据的Variant

             Boolean:包含True或False

             Byte:包含0到255之间的整数

             Integer:包含-32768到32767之间的整数

             Currency:货币类型

             Long:包含-2147483648到2147483647之间的整数

             Single:单精度浮点数

             Double:双精度浮点数

             Data(Time):包含表示日期的数字,日期范围从公元前100年1月1日到公元9999年12月31日

             String:包含变长字符串,最大长度可为20亿个字符

             Object:包含对象

             Error:包含错误号

             除简单的数字字符串以外,Variant可以进一步区分数值信息的特定含义。例如使用数值信息表示日期或时间。此类数据在与其他日期或时间数据一起使用时,结果也总是表示为日期或时间。从boolean值到浮点数,数值信息是多种多样的。Variant包含的数值信息类型称为子类型。大多数情况下,可将所需的数据放进Variant中,而Variant也会按照最适用与其包含的数据的方式进行操作。

    可以使用转换数函数来转换数据的子类型,另外,可以使用vartype的函数返回数据的Variant子类型。

    VBScript变量

    声明变量

             使用dim语句、public语句和private语句在脚本中显示声明变量,例如:dim username

             声明多个变量时,使用逗号分隔变量,例如:dim top , bottom , left , right

             如在同一行内给多个变量赋值,则不同变量之间用:分隔,如 a = 0 : b = 0

             另一种方式是通过直接在脚本中使用变量名这一简单方式隐式声明变量。这通常不是一个好习惯,因为这样有时会由于变量名被拼错而导致在运行脚本时出现意外的结果。因此,最好使用opinion explicit语句显示声明所有变量,并将其作为脚本的第一句。

    命名规则

             第一个字符必须是字母

             不能包含嵌入的句点

             长度不能超过255个字符

             在被声明的作用域内必须唯一

    Example1

    msgbox “Hello World!”

    Example2

    a = “Hello World!”

    msgbox varitype(a)

    Example3

    a = “Hello World!”

    b=1

    msgbox a+b(提示错误,类型不匹配! msgbox a & b)

    Example3

    opinion explicit ’(强制申明,如需使用,必须放在首行)

    dim hellomsg

    hellomsg=”hello world!”

    msgbox hellomsg

    标量变量和数组变量

    标量:只包含一个值的变量称为标量变量,如:a = 0

    数组变量:创建可以包含一系列值得变量,称为数组变量。声明数组变量时变量名后面有括号(),如dim A(10)。在VBScript中所有数组变量都是基于0,在基于0的数组中,数组元素的数目总是括号中显示的数目加1。这种数组称为固定大小的数组。

             要使用动态数组,必须随后使用redim确定维数和每一维的大小,使用preserve关键字在重新调整大小时保留数组的内容。重新调整动态数组大小的次数是没有任何限制的,尽管将数组的大小调小时,将会对视被删除元素的数据。

     

    Example3:数组的使用

    1.用for each表达式获取数组的每一个值

    dim a

    a = array(10.20.30)

    for each i in a

             msgbox i

    next

    2.用for循环构造数组

    dim arr(10)

    for i = 0 to ubound(arr)

             arr(i)=i

             msgbox arr(i)

    next

    msgbox “数组的上边界是:” & ubound(arr)

    msgbox “数组的上边界是:” & lbound(arr)

    3.VBS动态数组使用

    i = 0:nstr = ….

    dim myarray()

    do

             a = inputbox(“循环直到输入4为止”)

             ‘redim preserve myarray(i)

             redim myarray(i)

             myarray(i) = a

             i = i + 1

    loop untial a = “4”

    for i = 0 to ubound(myarray)

             nstr = nstr & myarray(i) & “,”

    next

    msgbox nstr

     

    VBScript常数

             常数是具有一定含义的名称,用于代替数字或字符串,其值被创建后就不允许再被改变。VBScript定义了许多内部函数。例如:msgbox “提示信息:” & vbcrlf & “操作成功” , vbinformation , “title”

    创建常数

             使用const语句在VBScript中创建用户自定义常数。使用const语句可以创建名称具有一定含义的字符串型或整数型常数,并给他们赋原义值,例如:

    const  conusername = “frank”

    const  pi = 3.14159

    const  conolympicdata = #08/08/08#

             最好采用一个命名方案一区分常量和变量,这样可以避免运行脚本时常数重新赋值。例如,可以用”vb”或”con”作常数名前缀,或将常数名的所有字母大写。将常量和变量区分开来可以在开发复杂的脚本时避免混乱。

     

    常用的常数

             vbcr 回车符    vblf 换行符    vbcrlf 回车符与换行符    vbnewline 新行字符

    VBScript运算符

    算数运算符

    比较运算符

    逻辑运算符

    求幂

    ^

    等于

    =

    逻辑非

    not

    负号

    -

    不等于

    <> 

    逻辑与

    and

    *

    小于

    逻辑或

    or

    /

    大于

    逻辑异或

    xor

    整除

    大于等于

    >=

    逻辑等价

    eqv

    求余

    mod

    小于等于

    <=

    逻辑隐含

    imp

    +

    对象引用比较

    is

     

     

    -

     

     

     

     

    字符串连接

    &

     

     

     

     

    VBScript条件语句

             使用条件语句和循环语句可以控制脚本的流程。使用条件语句可以编写进行判断和重复操作的VBScript代码。在VBScript中使用以下条件语句:

    if … then … else 语句,条件为true和false时分别运行某些语句

             条件为true时运行语句,例如:ifmydata < now  then  mydata = now  ‘单行不用加end if

             select case语句,对多个条件进行判断,例如:

    select case value

             case 1

                       msgbox “hello world!”

             case 2

                       msgbox “hello software testing! ”

             case 3

                       msgbox “hello 51testing!”

    end select

    VBScript循环语句

             循环用于重复执行一组语句。循环可分为三类:①在条件变为false之前重复执行语句;②条件变为true前重复执行语句;③按照指定的次数重复执行语句。

             在VBScript中可以使用下列循环语句:

    do…loop:当(或直到)条件为true是循环,退出循环用exit do

    while…wend:当条件为true时循环,while循环没有退出语句

    for…next:指定循环次数,使计数器重复运行语句,退出for语句用exit for。默认计数器每次加1,但可以用step关键字指定每次循环计数器增加的值。

    for each…next:对于集合中的每项或数组中的每个元素,重复执行一组语句。

     

    Example4

    for i = 0 to 10 step 3

             msgbox i

    next

    VBScript中的with语句

             对一个对象执行一系列的语句。

    语法:

    with object

             statement

    end with

     

    Example5

    with window(“计算器”)

             .einbutton(“7”.click)

             .einbutton(“+”.click)

             .einbutton(“6”.click)

             .einbutton(“=”.click)

    end with

             当程序一旦进入with块,object就不能改变。因此不能用一个with语句来设置多个不同的对象。with语句可以嵌套。

    VBScript过程

             在VBScript中,过程被分为两类:sub过程和function过程。

    sub过程

             sub过程是包含在sub和end sub语句之间的一组VBScript语句,执行操作但不返回值,sub过程可以使用参数(由调用过程传递的常数、变量或表达式)

             声明sub过程的名称、参数以及构成其主体的代码:

    [public [default] | private] sub name [(arglist)]

             [statement]

             [exit sub]

             [statement]

    end sub

    function过程

             function过程是包含在function和end function语句之间的一组VBScript语句。function过程与sun过程类似,但是function过程可以返回值。function过程可以使用参数(由调用过程传递的常数、变量或表达式)。function过程通过函数名返回一个值,这个值是在过程的语句中赋给函数的。function返回值的数据类型总是variant。

    声明function过程的名称、参数以及构成其主体的代码:

    [public [default] | private] function name [(arglist)]

             [statement]

             [name = expression]

             [exit function]

             [statement]

             [name = expression]

    end function

    Example5

    function getname(name)

             getname = name

    end function

    msgbox getname(“张三”)

     

    过程中的arglist参数:

             [byval | byref] varname[()]

             byval表示该参数按值传递

             byref表示该参数按引用传递,系统默认使用这种传值方式

             varname表示参数的变量名称,遵循标准标量命名规则

    过程的声明:

             没有显示地指定使用public或private,则sub/function过程默认为公用,即它们对于脚本的所有其他过程都是可见的。sub/function过程中局部变量的值在调用过程中不被保留。

    过程的调用:

             使用call语句调用(函数返回值将别丢失)

             直接输入过程名调用

             支持递归调用

     

    Example6:byval和byref的区别

    opinion explicit

    dim msg

    msg = “nice to meet you”

    changebyval msg

    msgbox msg

    changebyrefl msg

    msgbox msg

    function changebyrefl(byref  sentense)

             sentence = sentence & “,too”

    end function

    function changebyvall(byval  sentense)

             sentence = sentence & “,too”

    end function

    VBScript的编码规范

    编码约定

             1.对象、变量和过程的命名规范

                       匈牙利命名法:变量名=类型名+类型+对象描述

                       骆驼命名法:除首单词外其他首字母大写

                       帕斯卡命名法:所有单词首字母大写

             2.注释约定

                       不要在代码行的结尾处使用注释,要将注释放在单独的行

                       注释文本以大写字母开头

                       注释以句点结束

                       在注释分隔符(‘)和注释之间插入一个空格

                       请勿创建已设置格式的将注释包含在内的星号块

             3.文本格式和缩进指南

                       关键字空一格,运算符两边不加空格,括号内侧空一格

                       缩进四个空格为单位

                       函数之间空两行

                       语句块的配对对齐

    VBScript变量的命名规则

    类型

    前缀

    示例

    Variant

    var

    varArray

    Boolean

    bln

    blnFound

    Byte

    byt

    bytRasterData

    Date(Time)

    dtm

    dtmStart

    Double

    dbl

    dblTolerance

    Error

    err

    errOrdeNum

    Integer

    int

    intQuantity

    Long

    lng

    lngDistance

    Object

    obj

    objCurrent

    Single

    sng

    sngAverage

    String

    str

    strFirstName

    Example7:

    ‘**************************************

    ‘目的:在UserList数组中

                      ‘定位指定用户的首次出现。

    ‘输入:strUserList():要搜索的用户列表

                      ‘strTargetUser:要搜索的用户名。

    ‘返回:索引strUserList数组中

                      ‘strTargetUser的首次出现。

                      ‘如果找不到目标用户,则返回-1。

    ‘**************************************

    Function intFindUser(strUserList(), strTargetUser)

             Dim i  ‘loop counter

             Dim blnFound  ‘找到目标标志

             intFindUser = -1

             i = 0  ‘初始化循环计数器

             do while i < ubound(strUserList) and not blnfound

                      if strUserList(i) = strTargetUser then

                               blnfound = true  ‘将标志设置为true

                               intFindUser = i  ‘将返回值设置成循环计数

                      end if

                      i = i + 1  ‘递增循环计数器

             loop

    end function

    VBScript的常用函数

    字符串函数:

             len函数

             left函数

             mid函数

             right函数

             instr函数

             instrrev函数

             ltrim、rtrim和trim函数

             lcase函数

             ucase函数

             replace函数

             strcomp函数

             split函数

             join函数

    转换函数:

             asc函数

             chr函数

             str函数

             val函数

             cbool函数

             cbyte函数

             ccur函数

             cdte函数

             cdbl函数

             cint函数

             clng函数

             csng函数

             cstr函数

    判断函数:

             isarray函数

             isdata函数

             isempty函数

             isnumeric函数

             isnull函数

             isobject函数

             varitype函数

             typename函数

    时间函数:

             date函数

             day函数

             hour函数

             minute函数

             mounth函数

             now函数

             second函数

             time函数

             weekday函数

             weekdayname函数

             year函数

    其它函数:

             rnd函数和randomize语句

                       公式:int((upperbound – lowerbound + 1) * rnd + lowerbound)

                       例子:生成指定范围的10个随机数

             creatobject函数(注意使用set来给对象赋值)

                       set myobj = creatobject(“wscript.shell”)

                       set myobj = creatobject(“excel.application”)

                       set myobj = creatobject(“scripting.filesystemobject”)

                       set myobj = creatobject(“scripting.dictionary”)

                       set myobj = creatobject(“adodb.connection”)

                       set myobj = creatobject(“adodb.recondset”)

                       set myobj = creatobject(“microsoft.xmldom”)

                       set myobj = creatobject(“internetexplorer.application”)

             getobject函数

             int、fix函数

             lbound、ubound函数

             msgbox、inputbox函数

    Example8

    dim a(10)

    min = inputbox(“请输入下边界:”)

    min = inputbox(“请输入上边界:”)

    randomize

    for I = 0 to ubound(a) – 1

        a(i) = int((max – min + 1)*rnd + min)

        msgbox a(i)

    next

    小练习

    1.数组练习

             假设现在有一数组(”0”,”1”,”2”,”3”,”4”,”5”,”a”,”b”,”c”,”d”),用户可以输入一个值,程序判断用户输入的这个值是否在数组中。(使用两种方法实现)

    Dim arr, i, str

    arr = array("1", "2", "3", "4", "5", "a", "b", "c", "d")

    str = inputbox("输入字符","")

    if str <> ""  then

        for i = 0 To UBound(arr)

                 If arr(i) = str Then

                exit For

            end if

        Next

        if i <= UBound(arr) then

            msgbox  "数组中包含" & str

            else

            msgbox  "a数组中不包含" & str

        end if

    end if

    2.随机数

             用程序编写并生成4为随机验证码,验证码范围:大写字母、小写字母、数字。

    msgbox getranstring(4)

    function getranstring(byval ilen)

             dim i

             for i = 1 to ilen

                       getranstring = getranstring & generatevericode()

             next

    end function

    function

     generatevericode()

             dim iget

             iget = getrndnumber(1,3)

             select case iget

                       case 1

                                generatevericode = chr(getrndnumber(48,57))

                       case 2

                                generatevericode = chr(getrndnumber(65,90))

                       case 3

                                generatevericode = chr(getrndnumber(97,122))

                       case else

                                generatevericode = “err_code”

             end select

    end function

    function getrndnumber(byval lowerbound, byval upperbound)

             randomize

             getrndnumber = int((upperbound – lowerbound + 1) * rnd + lowerbound)

    end function

    VBScript中的文件读写

    1.文本文件的读写

    option explicit

    constforreading = 1, forwriting = 2, forappending = 8

    dim fso, file, msg

    set fso = fso.createobject(“scripting.filesystemobject”)

    set file = fso.opentextfile(“c:calc.text”, forreading)

    while (not file.atendofstream)

             msg = msg & file.readline & chr(13) & chr(10)

    wend

    msgbox msg

    file.close

    set file = nothing

    set fso = nothing

    2.Excel文件的读写

    dim xlapp, xlworkbook, xlsheet

    dim irowcount, iloop, numadd

    set xlapp = createobject(“excel.application”)

    xlapp.visible = true

    set xlworkbook = xlapp.workbooks.open(“c:data.xls”)

    set xlsheet = xlworkbook.sheets(“sheet1”)

    irowcount = xlsheet.usedrang.rows.count

    for iloop = 2 to irowcount

             numadd = xlsheet.cells(iloop, 1)

    next

    xlworkbook.save

    xlworkbook.close

    xlapp.quit

    set xlsheet = nothing

    set xlworkbook = nothing

    set xlapp = nothing

    3.数据库文件的读写

    dim cnn, rst, strcnn

    strcnn = “provider = Microsoft.jet.oledb.4.0; data sourse = c:calc.mdb; persist security info = false”

    set cnn = creatobject(“adodb.connection”)

    cnn.open strcnn

    set rst = createobject(“adodb.recordset”)

    rst.open “select * from calc”,cnn

    rst.movefirst

    do while not rst.eof

             msgbox trim(rst.fields(“testresult”))

             rst.movenext

    loop

    rst.close

    cnn.close

    set rst = nothing

    set cnn = nothing

    4.XML文件的读写

    dim xmldoc, xmlroot, rootchildltem, msg

    set xmldoc = createobject(“Microsoft.xmldom”)

    xmldoc.async = false

    xmldoc.load”c:calc.xml”

    if xmldoc.paeseerror.errorcode <> o then

             msgbox “xml loaded failed. the reson is:” & xmldoc.parseerror.reason

             exit sub

    end if

    set xmlroot = xmldoc.docunentelement

    if not xmlroot.haschildnodes then exit sub

    for each rootchildltem in xmlroot.childnodes

             if rootchildltem.nodename = “testcase” then

                       msg = msg & rootchildltem.firstchild.nodevalue & vbnewline

             end if

    next

    msgbox msg

  • 相关阅读:
    C 语言的读取文件
    [Water]序号呼唤
    [Water]Hdu 1022 Train Problem I
    [Water]Hdu 2054 A == B ?
    Java竞赛可能会用到的东西
    [Huffman]Hdu 2527 Safe Or Unsafe
    [Prim]Poj 1258 Agri-Net
    Hdu 1257 最少拦截系统 (LIS、贪心)
    [Max Sum]hdu 1003
    Hdu 2566 统计硬币
  • 原文地址:https://www.cnblogs.com/wont/p/4152635.html
Copyright © 2011-2022 走看看