QTP的那些事--WebList与正则表达式

Function IsRegEqual(s_Text, s_Pattern)
  Dim regEx, retVal ' 变量
  Set regEx = New RegExp ' 创建正则表达式 .
  regEx.Pattern = s_Pattern ' 模式
  regEx.IgnoreCase = True
  IsRegEqual = regEx.Test(s_Text)
End Function
Function SelectByText(objWebList,s_Text,b_RegExpression)
  Set obj_Options=objWebList.object.options
  i_Count =obj_Options.length - 1
  For i=0 to i_Count
    If b_RegExpression And IsRegEqual(obj_Options(i).text,"^"+ s_Text) Then
      obj_Options(i).selected=True
      Exit for
    Elseif Lcase(s_text)=Lcase(obj_Options(i).text) then
      obj_Options(i).selected=True
      Exit for
    End If
  Next
End Function
Function SelectByValue(objWebList,s_Value,b_RegExpression)
  Set obj_Options=objWebList.object.options
  i_Count =obj_Options.length - 1
  For i=0 to i_Count
    If b_RegExpression And IsRegEqual(obj_Options(i).value,"^" & s_Value) Then
      obj_Options(i).selected=True
      Exit for
    Elseif Lcase(s_text)=Lcase(obj_Options(i).value) then
      obj_Options(i).selected=True
      Exit for
    End If
  Next
End Function
Function SelectByIndex(objWebList,i_Index)
  objWebList.object.options(i_Index).selected=True
End Function
下面是例子:
SelectByText Browser("Find a Flight: Mercury").Page("Find a Flight: Mercury").WebList("fromPort"),".*ond.*",TRUE
SelectByValue Browser("Find a Flight: Mercury").Page("Find a Flight: Mercury").WebList("fromPort"),"san.*francisco",TRUE
SelectByIndex Browser("Find a Flight: Mercury").Page("Find a Flight: Mercury").WebList("fromPort"),3

第二种方法是:

'Select WinList中选项时支持使用正则表达式
Function RegExpSelect(objWinList, strPattern)
Dim objRegExp, arrAllItems, intIndex
'创建正则表达式对象,设置区分大小写
Set objRegExp = New RegExp
objRegExp.IgnoreCase = False
objRegExp.Pattern = strPattern
'取到WinList下的所有选项的文本,赋值到数组
arrAllItems = Split(objWinList.GetROProperty("all items"), VbLf)
'遍历选项数组
For intIndex = 0 To UBound(arrAllItems)
  '判断表达式是否能匹配当前选项,能匹配则选中之,否则继续循环
  If objRegExp.Test(arrAllItems(intIndex)) Then
   objWinList.Select intIndex
   Reporter.ReportEvent micPass, "RegExpSelect Successful", "Pattern=" & strPattern & "   First Matched Item=" & arrAllItems(intIndex)
   Set objRegExp = Nothing
   Exit Function
  End If
Next
'若遍历完所有选项都不能匹配,则报出不能匹配的错误,写入日志中
Reporter.ReportEvent micFail, "RegExpSelect Failed ", "No Item Matched, Pattern=" & strPattern
End Function

 

以下为QTP中的注册自己的函数:

'将RegExpSelect函数注册到WinList的方法中去
RegisterUserFunc "WinList", "RegExpSelect", "RegExpSelect"
'在WinList中使用RegExpSelect方法,选择第一个能符合表达式的选项
'比如这里希望能自动选一个上午10点到12点间Portland飞往Los Angeles且价格低于180美金的航班
Window("Flight Reservation").Dialog("Flights Table").WinList("From").RegExpSelect "\d+ POR 1[01]:[0-5][0-9] AM LAX \d{2}:\d{2} [AP]M \w+ \$1[0-7]\d\.\d{2}"

转载于:https://www.cnblogs.com/alterhu/archive/2012/03/25/2416999.html

猜你喜欢

转载自blog.csdn.net/weixin_33755557/article/details/94029488