qtp tips(转)
1、Object Spy的Tips
Hold the CTRL key to change the window focus or perform other mouse operations
2、QTP为什么无法单步调试?
安装Microsoft Script Debuger即可
3、QTP如何访问Oracle数据库?

'========================================================================== ' Name: GetDataFromDB ' Summary: Get data from Database ' Parameters: DBpassword, DBuser, DBserver, ColumnArray ' Outputs: If success, returnStr; If not, 0 ' Example: returnStr = "SKU=A9P21A8R|ENG_DESC=HP CPQ LA2405x 24-In LED Rfrbd Monitor|SKU=A9P21A8R#ABA|ENG_DESC=HP CPQ LA2405x 24-In LED Rfrbd Monitor " '========================================================================== Public Function GetDataFromDB(DBpassword, DBuser, DBserver, TableName, ColumnArray_str, QueryCondition) Dim db_conn,db_res, returnStr, ColumnArray, Col_value db_str="Password="&DBpassword&";User ID="&DBuser&";Data Source="&DBserver sql_str="select " ColumnArray=Split(ColumnArray_str,"|") For i=0 To UBound(ColumnArray)-1 sql_str = sql_str&ColumnArray(i)&"," Next ' sql_str = sql_str&replace(ColumnArray_str,"|",",") sql_str = sql_str&ColumnArray(i) sql_str = sql_str&" from "&TableName&" where "&QueryCondition 'msgbox(sql_str) Set db_conn= createobject("ADODB.Connection") db_conn.Open"Provider=oraoledb.oracle.1;"&db_str&";Persist Security Info=True" If db_conn.State = 0 Then Reporter.ReportEvent micFail, "DB Connection Test", "Connect DB failed!" GetDataFromDB = 0 Else Reporter.ReportEvent micPass, "DB Connection Test", "Connect DB successfully!" Set db_res= createobject("ADODB.RecordSet") db_res.Open sql_str,db_conn,2,3 'db_res.MoveFirst Do while Not db_res.EOF For j=0 To i Col_value = db_res(j).value returnStr = returnStr&"|"&db_res(j).name&"="&Col_value ' returnStr = returnStr&"|"&db_res(j).name&"="&db_res(j).value&"A" Next db_res.MoveNext Loop db_res.close db_conn.close Set db_res=Nothing Set db_conn=Nothing 'msgbox(returnStr) GetDataFromDB = returnStr End If End Function
如果是sql server数据库,
db_str = "DRIVER=SQL Server;SERVER="&DBserver&";UID="&DBuser&";PWD="&DBpassword&";DATABASE="&strDatabase
4、如何全选所有WebCheckBox对象?
Dim oWebChkDesc
Set oWebChkDesc = Description.Create
oWebChkDesc("micclass").value = "WebCheckBox"
oWebChkDesc("html tag").Value = "INPUT"
' 获取所有匹配描述的对象
Dim allCheck, oCheckBox
Set allCheck = Browser("Web Tours").Page("Web Tours").ChildObjects(oWebChkDesc)
For i = 0 to allCheck.Count - 1
Set oCheckBox = allCheck(i)
oCheckBox.Set "ON"
Next
5、QTP9.2录制脚本问题:运行QTP,点击录制钮进行脚本录制,但是IE浏览器打开后几秒钟,又自动关闭了,不知道为什么?
QTP9.2支持的IE浏览器版本:
Microsoft Internet Explorer 6.0 Service Pack 1
Microsoft Internet Explorer 7.0
6、Action之间无法传递数组
用全局的Dictionary对象来存储数据,这样可以在多个Action之间共用数据
参考:
http://blog.csdn.net/Testing_is_believing/archive/2010/01/08/5161955.aspx
http://blog.csdn.net/Testing_is_believing/archive/2008/06/09/2528094.aspx
也可以这样:
建一个vbs文件,定义变量,在Setting—>Resources导入这个VBS文件
在主Action里面 给变量赋值
在子Action中调用这个变量
这个变量的内存相当于共享
7、QTP脚本编辑器中可以修改Tab键跳转的格数吗?
编辑脚本时,总感觉Tab一次,移动的格数太少
Tools -> View Options
8、如何在VBScript中调用QTP脚本
现在有一个用QTP录制好的脚本,但是想用VBS来调用,如何调用?

Dim qtApp 'As QuickTest.Application ' Declare the Application object variable Dim qtTest 'As QuickTest.Test ' Declare a Test object variable Dim qtResultsOpt 'As QuickTest.RunResultsOptions ' Declare a Run Results Options object variable Set qtApp = CreateObject("QuickTest.Application") ' Create the Application object qtApp.Launch ' Start QuickTest qtApp.Visible = True ' Make the QuickTest application visible ' Set QuickTest run options qtApp.Options.Run.ImageCaptureForTestResults = "OnError" qtApp.Options.Run.RunMode = "Fast" qtApp.Options.Run.ViewResults = False qtApp.Open "C:\Tests\Test1", True ' Open the test in read-only mode ' set run settings for the test Set qtTest = qtApp.Test qtTest.Settings.Run.IterationMode = "rngIterations" ' Run only iterations 2 to 4 qtTest.Settings.Run.StartIteration = 2 qtTest.Settings.Run.EndIteration = 4 qtTest.Settings.Run.OnError = "NextStep" ' Instruct QuickTest to perform next step when error occurs Set qtResultsOpt = CreateObject("QuickTest.RunResultsOptions") ' Create the Run Results Options object qtResultsOpt.ResultsLocation = "C:\Tests\Test1\Res1" ' Set the results location qtTest.Run qtResultsOpt ' Run the test MsgBox qtTest.LastRunResults.Status ' Check the results of the test run qtTest.Close ' Close the test Set qtResultsOpt = Nothing ' Release the Run Results Options object Set qtTest = Nothing ' Release the Test object Set qtApp = Nothing ' Release the Application object
9、没安装QTP打开QTP脚本的方法
QTP的脚本在每个action的根目录下的Script.mts文件,用UltraEdit或记事本等工具打开就可以看到。
10、QTP支持的正则表达式
使用反斜杠字符 ( \ )
匹配任意单个字符 ( . )
匹配列表中的任意单个字符 ( [xy] )
匹配不在列表中的任意单个字符 ( [^xy] )
匹配某个范围内的任意单个字符 ( [x-y] )
特定字符的零次或多次匹配 ( * )
特定字符的一次或多次匹配 ( + )
特定字符的零次或一次匹配 ( ? )
对正则表达式进行分组 ( ( ) )
匹配几个正则表达式中的一个表达式 ( | )
在一行的开始进行匹配 ( ^ )
在一行的结尾进行匹配 ( $ )
匹配包括下划线在内的任一字母数字字符 ( \w )
匹配任意非字母数字字符 ( \W )
11、如何判断Excel进程是否存在?
如何判断Excel进程是否存在?如果存在则关闭Excel进程。
SystemUtil.CloseProcessByName "excel.exe"
On error resume next
Dim Obj
Set Obj = GetObject(,"Excel.Application")
If Not Obj Is Nothing Then
Obj.Quit
Set Obj = Nothing
End If
或者:
' To kill excel application
CreateObject("WScript.Shell").Run "taskkill /f /im excel.exe"
'To check if excel is running use this function
msgbox "Excel is Running:" & FindProcess("EXCEL.EXE")
Function FindProcess(ByVal ProcessName)
FindProcess= False
Set Shell = CreateObject("WScript.Shell")
Set ShellResult = Shell.Exec("TaskList")
While Not ShellResult.StdOut.AtEndOfStream
If Instr(UCASE(ShellResult.StdOut.ReadLine),UCASE(ProcessName)) Then
FindProcess = True
Exit Function
End If
Wend
End Function
12、如何在浏览器对象的指定位置按右键?
hwnd = Browser("Browser").GetROProperty("hwnd")
window("hwnd:=" & hwnd).Click 12,6,micRightBtn
13、怎样在QTP中关闭Windows防火墙?
' Disable the Firewall
Set objFirewall = CreateObject("HNetCfg.FwMgr")
Set objPolicy = objFirewall.LocalPolicy.CurrentProfile
objPolicy.FirewallEnabled = FALSE
Set objPolicy = Nothing
Set objFirewall = Nothing
14、如何使用QTP检查电脑中某目录是否存在?
Dim fso, msg,fldr
fldr = "D:\books"
Set fso = CreateObject("Scripting.FileSystemObject")
If (fso.FolderExists(fldr)) Then
msg = fldr & " exists."
Else
msg = fldr & " doesn't exist."
End If
Msgbox msg
15、QTP菜单丢失的问题
QTP用了一段时间菜单怎么没了呢?重置一下Toolbars,应该就可以了
16、如何判断注册表HKEY_CURRENT_USER\Software\WinRAR是否存在?
Dim WshShell, bKey
Set WshShell = CreateObject("WScript.Shell")
ON Error Resume Next
bKey = WshShell.RegRead("HKEY_CURRENT_USER\Software\WinRAR\")
'bKey = WshShell.RegRead("HKEY_LOCAL_MACHINE\SOFTWARE\ORACLE\KEY_OraDb10g_home1\ORACLE_HOME_NAME")
If bKey = vbEmpty Then
Msgbox "Key Not Exists!"
End IF
Set WshShell=Nothing
17、QTP中怎么测试邮件激活功能时?
测试一个用户注册的功能,注册后会发送一封邮件到注册的邮箱,完了需要用户到邮箱查看,通过一个链接激活后,才算注册成功,这个功能如何用QTP实现自动化?
可下载个JMail组件,然后在QTP中连接邮箱,接收邮件,再分析邮件内容,解析出链接来,然后发送WEB页面请求该链接的URL
附JMail接收邮件的脚本:
Set pop3 = CreateObject("JMail.POP3")
pop3.Connect "xxx","xxx","pop.126.com"
Print "邮件总数:" & pop3.Count
Set msg = pop3.Messages.Item(1)
Print msg.Subject
Print msg.FromName
Print msg.Body
Set pop3 = Nothing
18、QTP中如何压缩文件和解压缩文件?
例如在D:\test下面有10个txt文件,文件名分别为1.txt 2.txt 3.txt依次类推
能否在QTP中先把它们压缩,然后再解压缩?
Set objWsh = CreateObject("Wscript.shell")
'压缩
objWsh.Run "winrar a D:\test\test.rar D:\test\*.txt",0,True
'解压缩
objWsh.Run "winrar x -o+ D:\test\test.rar *.txt D:\test\",0,True
Set objWsh = Nothing
19、如何在QTP中启动网络、断开网络
下面的代码可用于停用和启用网络连接(名字可能需要根据实际的进行修改):

Const ssfCONTROLS = 3 sConnectionName = "无线网络连接" sEnableVerb = "启用(&A)" sDisableVerb = "停用(&B)" set shellApp = createobject("shell.application") set oControlPanel = shellApp.Namespace(ssfCONTROLS) set oNetConnections = nothing for each folderitem in oControlPanel.items if folderitem.name = "网络连接" then set oNetConnections = folderitem.getfolder: exit for end if next if oNetConnections is nothing then msgbox "未找到网络和拨号连接文件夹" wscript.quit end if set oLanConnection = nothing for each folderitem in oNetConnections.items if lcase(folderitem.name) = lcase(sConnectionName) then set oLanConnection = folderitem: exit for end if next if oLanConnection is nothing then msgbox "未找到 '" & sConnectionName & "' item" wscript.quit end if bEnabled = true set oEnableVerb = nothing set oDisableVerb = nothing s = "Verbs: " & vbcrlf for each verb in oLanConnection.verbs s = s & vbcrlf & verb.name if verb.name = sEnableVerb then set oEnableVerb = verb bEnabled = false end if if verb.name = sDisableVerb then set oDisableVerb = verb end if next 'debugging displays left just in case... ' 'msgbox s ': wscript.quit 'msgbox "Enabled: " & bEnabled ': wscript.quit 'not sure why, but invokeverb always seemed to work 'for enable but not disable. ' 'saving a reference to the appropriate verb object 'and calling the DoIt method always seems to work. ' if bEnabled then ' oLanConnection.invokeverb sDisableVerb oDisableVerb.DoIt else ' oLanConnection.invokeverb sEnableVerb oEnableVerb.DoIt end if 'adjust the sleep duration below as needed... ' 'if you let the oLanConnection go out of scope 'and be destroyed too soon, the action of the verb 'may not take... ' wscript.sleep 400
20、QTP怎么检测XML文档?
(1)使用XMLUtil对象。
XMLUtil对象用于读取XML文件,其LoadFile方法可从指定的文件中读入XML格式的文本,返回XMLData对象,例如,下面的脚本:
' 使用XMLUtil对象的CreateXML方法来创建XMLData对象
Set doc = XMLUtil.CreateXML()
' 加载XML文件用于检查
doc.LoadFile "Test.XML"
可用Validate方法来指定某个Schema文件,检查加载的XML文件是否满足Schema的格式要求,例如,下面的脚本检查对象库导出的XML文件是否满足ObjectRepository.xsd的要求:
'检查XML文档是否满足指定的XML schema
ans = doc.Validate ("D:\Program Files\Mercury Interactive\QuickTest Professional\dat\ObjectRepository.xsd")
'如果检查满足Schema,则提示检查成功,否则列出不满足的原因
If ans Then
MsgBox "XML文件匹配指定的Schema!"
else
errNo = doc.GetValidationErrorsNumber
For i = 1 to errNo
errStr = doc.GetValidationError(i)
MsgBox errStr
Next
End If
(2)利用XMLDOM对象来加载XML数据进行分析。
XMLDOM是用来访问和操作XML文档的编程接口规范。XMLDOM被设计为可用于任何语言和任何操作系统。借助DOM,我们可以通过VBScript创建XML文档对象,遍历其结构,增、改、删其元素。DOM将整个XML文档视作一棵树,文档级的元素是树的根。
XMLDOM包含四个主要对象:XMLDOMDocument、XMLDOMNode、XMLDOMNodeList、XMLDOMNamedNodeMap。每个XMLDOM对象有其自己的特性和方法。
下面的例子通过XMLDOM对象加载XML文件,修改指定节点的值,然后保存到另外一个XML文件:
Set xmlDoc = CreateObject("Microsoft.XMLDOM") ' 创建XMLDOM对象
xmlDoc.async = False
xmlDoc.load "test.xml" ' 加载XML文档
' 检查XML文档是否有错误
If xmlDoc.parseError.errorCode <> 0 Then
Set myErr = xmlDoc.parseError
MsgBox("XML Loads Failed. " & myErr.reason)
Else
Set rootNode = xmlDoc.documentElement
' 修改XML指定节点的某个属性的值
rootNode.childNodes(0).childNodes(0).childNodes(0).attributes(4).nodeValue = "E-Mail"
Print rootNode.childNodes(0).childNodes(0).childNodes(0).attributes(4).nodeValue ' 打印修改后的节点值
rootNode.childNodes(0).childNodes(0).childNodes(0).attributes(5).nodeValue = "hello!" '修改节点值
Print rootNode.childNodes(0).childNodes(0).childNodes(0).attributes(5).nodeValue '打印修改后的节点值
' 保存xml数据到另外一个文件
xmlDoc.save "test_save.xml"
End If
Set xmlDoc = Nothing
21、WEB页面中的Image按钮对象动态变化,在脚本运行时会有问题
http://www.beebuyer.com/c/270-Formal-Special-Occasion-Dresses 这个网址,点击“add to cart”后按钮变成“check cart”就是这个按钮过不去。
这是对象动态 变化了
add to cart已经被智能识别出来了,check_cart_icon是后面动态生成的对象,之前加个Wait语句等待它生成即可:
Browser("China Wholesale Formal,").Page("China Wholesale Formal,").Image("add to cart").Click
Wait 2
Browser("China Wholesale Formal,").Page("China Wholesale Formal,").Image("check_cart_icon").Click
也可以这样:
Do until Browser("China Wholesale Formal,").Page("China Wholesale Formal,").Image("check_cart_icon").Exist(2)
Loop
22、QTP连接DB2出现的58004错误提示问题怎么解决?
提示错误:
[IBM][CLI Driver] SQL1042C 发生意外的系统错误。 SQLSTATE=58004
I have a problem in connecing QTP to DB2 and fetch query results.
--------------------------------------------------------------------------------
Problem Description: Error: "[IBM][CLI Driver] SQL 1042C An unexpected system error occured. SQLSTATE=58004"
The user receives a "[IBM][CLI Driver] SQL 1042C An unexpected system error occured. SQLSTATE=58004" error message when trying to connect to an IBM DB2 client using a Database Checkpoint or ADODB statements within the script.
Diagnosis: The existence of the <Quicktest Professional>/bin/QTPro.exe.Local file conflicts with the ability of ADODB to open the DB2 client.
--------------------------------------------------------------------------------
Solution: Rename the QTPro.exe.Local file in the bin directory
The QTPro.exe.Local file is used for redirection of DLLs that QuickTest Professional loads. In the case of coexistence problems with other Mercury products, the file instructs Windows API to load DLLs from the <QuickTest Professional>\bin directory instead of other directories. This is important for the coexistence between QuickTest Professional, LoadRunner, and old versions of Astra LoadTest.
Renaming this file should solve the problem. QuickTest Professional will work fine without QTPro.exe.Local, unless LoadRunner or Astra LoadTest are installed on the machine.
1. Close QuickTest Professional.
2. Open Windows Explorer, and navigate to the QuickTest Professional installation directory.
3. In the bin directory, locate the QTPro.exe.Local file, and rename it (for example, QTPro.exe.Local.old).
4. Restart QuickTest Professional.
After renaming the file, QuickTest Professional should be able to connect to the database and work with it as expected. If the error continues, try removing unneeded parameters in the connection string.
23、如何把一个Excel中的Sheet页数据拷贝到另外一个Excel的Sheet页中?
Set objExcel = CreateObject("Excel.Application")
objExcel.Visible = True
Set objWorkbook1= objExcel.Workbooks.Open("D:\1.xls")
Set objWorkbook2= objExcel.Workbooks.Open("D:\2.xls")
objWorkbook1.Worksheets("Sheet1").UsedRange.Copy
objWorkbook2.Worksheets("Sheet2").Range("A1").PasteSpecial'Paste =xlValues
objWorkbook1.Save
objWorkbook2.Save
objWorkbook1.Close
objWorkbook2.Close
objExcel.Quit
set objExcel=nothing
24、如何设置WinButton的Enable属性为False?
Win类型的对象不支持用SetROProperty这种设置属性的方法
可以用WinAPI中的EnableWindow来设置按钮是否可用。例如:
Extern.Declare micInteger,"EnableWindow","user32.dll","EnableWindow",micHwnd,micInteger
windowName="计算器"
hWnd = Extern.FindWindow(null,windowName)
Window( "hwnd:=" & hwnd ).Activate micLeftBtn
buttonHwnd = Window( "hwnd:=" & hwnd ).WinButton("text:=1").GetROProperty("hwnd")
Extern.EnableWindow buttonHwnd,False
25、QTP的Browser对象部分方法失效的问题
部分Browser方法,如Navigate、Back、Home、Refresh等在某些人的机器上是好用的,但在另外一些人的机器上就不好用了。脚本执行到这些方法,并不会抛出错误;而且qtp日志里看到的状态是"done"。
经过观察发现这些机器上IE加载项(IE"工具"->"管理加载项")的不同:
BHOManager Class插件的问题。文件名是BHOManager.dll,部分人的机器上该插件被禁用或删除掉了,猜测原因可能是使用了某些清理ie的工具导致。
解决该问题的方法很简单:
如果是被禁用了,只要重新启用即可;如果是被删除掉了,可以重新安装qtp,或者从别处拷贝BHOManager.dll文件过来,用regsvr32 BHOManager.dll注册后就可以了。
26、如何修改QTP脚本默认打开/保存的目录?
QTP脚本开发,每次都要打开文件夹,却总是默认从C:\Program Files\Mercury Interactive\QuickTest Professional\Tests来找文件,
默认的目录是可以修改的,只要修改注册表:
1, HKEY_current_user\software\MI\QTP\mictest\TestsDirectory
2, HKEY_local_machine\software\MI\QTP\mictest\TestsDirectory
修改为:自定义的文件夹,重启QTP即可看到打开文件夹已经修改为自定义的目录
27、如何修改Windows分辨率?
用C#编写一个DLL:

using System; using System.Runtime.InteropServices; namespace ScreenDisplaySetting { public class ChangeResulution { [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] public struct DEVMODE { [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)] public string dmDeviceName; public short dmSpecVersion; public short dmDriverVersion; public short dmSize; public short dmDriverExtra; public int dmFields; public short dmOrientation; public short dmPaperSize; public short dmPaperLength; public short dmPaperWidth; public short dmScale; public short dmCopies; public short dmDefaultSource; public short dmPrintQuality; public short dmColor; public short dmDuplex; public short dmYResolution; public short dmTTOption; public short dmCollate; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)] public string dmFormName; public short dmLogPixels; public int dmBitsPerPel; public int dmPelsWidth; public int dmPelsHeight; public int dmDisplayFlags; public int dmDisplayFrequency; } [DllImport("user32.dll", CharSet = CharSet.Auto)] static extern int ChangeDisplaySettings([In] ref DEVMODE lpDevMode, int dwFlags); [DllImport("user32.dll", CharSet = CharSet.Auto)] static extern bool EnumDisplaySettings(string lpszDeviceName, Int32 iModeNum, ref DEVMODE lpDevMode); public void ChangeRes( int width,int height ,int frequency ,int BitsPerPel) { DEVMODE DevM = new DEVMODE(); DevM.dmSize = (short)Marshal.SizeOf(typeof(DEVMODE)); bool mybool; mybool = EnumDisplaySettings(null, 0, ref DevM); DevM.dmPelsWidth = width;//宽 DevM.dmPelsHeight = height;//高 DevM.dmDisplayFrequency = frequency;//刷新频率 DevM.dmBitsPerPel = BitsPerPel;//颜色象素 long result = ChangeDisplaySettings(ref DevM, 0); } } }
然后在QTP中使用以下脚本来修改分辨率
Set var_CreateInstance = DotNetFactory.CreateInstance("ScreenDisplaySetting.ChangeResulution","E:\ScreenDisplaySetting.dll")
var_CreateInstance.ChangeRes 1024,768,60,32 ' 参数分别代表 宽、高、刷新率、颜色质量
Set var_CreateInstance = Nothing
28、QTP如何上传文件到FTP服务器?
可利用wininet.dll的相关函数来实现:

Const DEFAULT_FTP_PORT =21 Const SERVICE_FTP = 1 Const OPEN_TYPE_DIRECT = 1 Const FTP_TRANSFER_TYPE_ASCII = 1 Extern.Declare micLong,"InternetOpen","wininet.dll","InternetOpenA",micString,micDWord,micString,micString,micDWord Extern.Declare micLong,"InternetConnect","wininet.dll","InternetConnectA",micLong,micString,micInteger,micString,micString,micDWord,micDWord,micDWord Extern.Declare micInteger,"FtpGetFile","wininet.dll","FtpGetFileA",micLong,micString,micString,micInteger,micDWord,micDWord,micDWord Extern.Declare micInteger,"FtpPutFile","wininet.dll","FtpPutFileA",micLong,micString,micString,micDWord Extern.Declare micInteger,"InternetCloseHandle","wininet.dll","InternetCloseHandle",micLong ' 打开 hInternet = Extern.InternetOpen("QTP_FTP",OPEN_TYPE_DIRECT,vbNullChar,vbNullChar,0) If hInternet=0 Then Print("QTP_FTP:Failed to setup FTP environment.") ' 连接 hConnection = Extern.InternetConnect(hInternet,"www.atstudy.com",DEFAULT_FTP_PORT,"user1","user1",1,0,0) If hConnection =0 Then Print("Failed to setup FTP environment") ' 上传 ' bRetval = Extern.FtpPutFile(hConnection,sLocalFile,sRemoteFile,0) ' 下载 bRetval = Extern.FtpGetFile(hConnection,"/Mercury/QuickTest/QTP crack.rar","D:\QTP crack.rar",0,0,1,0) If Not CBool(bRetVal) Then Reporter.ReportEvent micFail,"FTP:FtpGetFile function","Failed to open download file." else Print("FTP:File :QTP crack.rar downloaded successfully") 'Reporter.ReportEvent micPass,"FTP:FtpPutFile function","FTP:File"&sLocalFile&"upload successfully." End If ' 关闭 Extern.InternetCloseHandle(hConnection) Extern.InternetCloseHandle(hInternet)
29、QTP webtable单元格赋值问题
在编写QTP代码过程中,对于WEBTABLE类型,不知道怎么赋值
可以用Set objLink = objTable.ChildItem(intRow, intCol, "WebElement" , 0)获得对象,因为点击后,此单元格变成可写的webedit类型,即objLink 这个对象直接set值肯定不行,目前不知道怎么去实现?
Set objLink = objTable.ChildItem(intRow, intCol, "WebElement" , 0)
objLink.Click
再用SendKeys或者Mercury.DeviceReplay来发送字符串输入
30、QTP能不能自动加上with...end with 语句?
一大堆代码要手动改成with...end with 语句来提高执行效率, 问一下QTP有没有这个功能可以自动修改呢?
Edit --> Advanced --> Apply "With" to script...
31、关闭多个浏览器窗口
例1

Dim i i = 0 while (Window("Text:=Yahoo! - Microsoft Internet Explorer", "index:="&i).exist) Window("Text:=Yahoo! - Microsoft Internet Explorer", "index:="&i).close i = i +1 wend
例2:

Dim oBrowserDesc, oBrowsers, iBrowserCount, iBrowserIndex, sBrowserName Set oBrowserDesc = Description.Create oBrowserDesc("micclass").Value = "Browser" Set oBrowsers = Desktop.ChildObjects(oBrowserDesc) iBrowserCount = oBrowsers.Count If iBrowserCount = 0 Then 'Print "当前没有浏览器打开" Else 'Print "浏览器个数: " & cStr(iBrowserCount) For iBrowserIndex = 0 To iBrowserCount - 1 'sBrowserName = oBrowsers(iBrowserIndex).getroproperty("name") 'Print "正在关闭: " & sBrowserName oBrowsers(iBrowserIndex).Close Next End If Set oBrowsers = Nothing Set oBrowserDesc = Nothing
33、怎么用QTP随机获得键盘的输入值,主要是字符,数字,标点符号,常用符号等

Msgbox GetRandomChar2 Function GetRandomChar() Dim StrArray StrArray = Array("1","2","3","4","5","6","7","8","9","0","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z") Randomize ub = Ubound(StrArray) idx =Int( ( ub - 0 + 1 ) * Rnd +0) GetRandomChar = StrArray(idx ) End Function Function GetRandomChar2() Randomize idx =Int( ( ub - 32 + 126 ) * Rnd +32) GetRandomChar2 = Chr(idx) End Function
36、如何使用HTML DOM进行自动化测试?
测试Google的小例子:

Dim oIee, objedit Dim oPagtxt Set oIee = CreateObject("InternetExplorer.Application") oIee.navigate ("http://www.google.com.hk") oIee.Visible = True Do While oIee.readystate <> 4 Loop Set oPagtxt = oIee.document set objedit = oPagtxt.getelementsbyname("q") objedit(0).value = "QTP自动化测试进阶" set objbutton = oPagtxt.getelementsbyname("btnG") objbutton(0).Click Set oIee = Nothing
37、为什么QTP录制了网页的 后退 功能后,回放时运行出错?
Browser().Back是可以后退的,可能你的浏览器重置过
工具->Internet选项->程序->管理加载项,选择“Internet Explorer 已经使用的加载项”,查找“BHOManager Class”,在下面的“设置”中选择“启用”,重启IE就可以了。
39、WinMenu如何获取所有菜单项?

Set obj_Menu = VbWindow("frm_main").WinMenu("Menu") GetNamesRec "", obj_Menu ' Open All Menus and Sub-Menus and Write the Menu Names in the Results Function GetNamesRec(itemPath, menuObj) ret = 0 lbl = menuObj.GetItemProperty(itemPath, "Label") Reporter.ReportEvent 0, itemPath & " label", lbl ret = menuObj.GetItemProperty(itemPath, "HasSubMenu") If ret Then cnt = menuObj.GetItemProperty(itemPath, "SubMenuCount") Reporter.ReportEvent 0, itemPath & " sub-menu items", cnt For n = 1 To cnt Path = menuObj.BuildMenuPath(itemPath, n) GetNamesRec Path, menuObj Next End If End Function
41、如何获取两个时间的差?
dim time1,time2,time3
time1=TimeValue("17:32:44")
time2=TimeValue("17:32:51")
Msgbox DateDiff("s",time1,time2)
44、vbs中处理日期格式
例如date返回的是2010-8-20日,现在我想要08-20-2010
msgbox DatePart("m",date)&"-"&DatePart("d",date)&"-"&DatePart("yyyy",date)
45、QTP目录中MSR.fbr文件能否删除?
MSR.fbr是运行过程中屏幕录像文件,如果不需要,可以删除。或者也取消生成MSR.fbr,在QTP-Tools-Options-Run中,取消勾选Save Movie to results (QTP9.2)
46、如何在QTP中利用HTTP请求-响应来检查WEB页面链接?

1 '=================================================================== 2 ' Name: CheckAllLinkReachable 3 ' Summary: CheckAllLinkReachable 4 ' Parameters: 5 ' strBrowser: browser name 6 ' strPage: page name 7 ' strURLPattern: URL pattern you wan't to check. such as: ^http.* 8 ' Return: None 9 '=================================================================== 10 Function CheckAllLinkReachable(strBrowser, strPage, strURLPattern) 11 Dim blnReachable 12 blnReachable = True 13 Set objXML = CreateObject("Msxml2.XMLHTTP") 14 ' Get all link on the page 15 Set objDes = Description.Create 16 objDes("micclass").Value = "Link" 17 Set objLinkList = Browser(strBrowser).Page(strPage).ChildObjects(objDes) 18 For i = 0 To objLinkList.Count() - 1 19 ' Create XML HTTP Object 20 strURL = objLinkList(i).GetROProperty("href") 21 If RegExpTest(strURLPattern, strURL) Then 22 objXML.Open "POST", strURL, false 23 objXML.Send 24 ' msgbox objXML.responseText 25 print (objLinkList(i).GetROProperty("href") & " Ready State:" & objXML.readyState & " Status: " & objXML.status) 26 If objXML.status <> "200" Then 27 blnReachable = False 28 End If 29 objXML.abort() 30 End If 31 Next 32 Set objXML = Nothing 33 CheckAllLinkReachable = blnReachable 34 End Function
47、如何在QTP中压缩文件?
Call fZip("D:\testZip","D:\testZip.zip")
1)用vbs的方式

1 Function fZip(ByVal mySourceDir, ByVal myZipFile) 2 Set fso = CreateObject("Scripting.FileSystemObject") 3 If fso.GetExtensionName(myZipFile) <> "zip" Then 4 Exit Function 5 ElseIf fso.FolderExists(mySourceDir) Then 6 FType = "Folder" 7 ElseIf fso.FileExists(mySourceDir) Then 8 FType = "File" 9 FileName = fso.GetFileName(mySourceDir) 10 FolderPath = Left(mySourceDir, Len(mySourceDir) - Len(FileName)) 11 Else 12 Exit Function 13 End If 14 Set f = fso.CreateTextFile(myZipFile, True) 15 f.Write "PK" & Chr(5) & Chr(6) & String(18, Chr(0)) 16 f.Close 17 Set objShell = CreateObject("Shell.Application") 18 Select Case Ftype 19 Case "Folder" 20 Set objSource = objShell.NameSpace(mySourceDir) 21 Set objFolderItem = objSource.Items() 22 Case "File" 23 Set objSource = objShell.NameSpace(FolderPath) 24 Set objFolderItem = objSource.ParseName(FileName) 25 End Select 26 Set objTarget = objShell.NameSpace(myZipFile) 27 intOptions = 256 28 objTarget.CopyHere objFolderItem, intOptions 29 iErr = Err.Number 30 31 On Error GoTo 0 32 If iErr <> 0 Then 33 fZip = iErr 34 Exit Function 35 End If 36 'Because the copying occurs in a separate process, the script will just continue. Run a DO...LOOP to prevent the function from exiting until the file is finished zipping. 37 Do 38 wait 1 39 Loop Until objTarget.Items.Count > 0 40 End Function
2) 用SystemUtil.Run的功能

CompressFile "c:/attachment.txt","c:/attachment.rar" Function CompressFile(soursefile,targetfile) On error resume next CompressFile = false m1 = chr(34) &targetfile& chr(34) m2 = chr(34) & soursefile& chr(34) command = "a -EP" & " " & m1 & " " & m2 SystemUtil.Run "winrar.exe",command Set fso = CreateObject("Scripting.FileSystemObject") For i = 0 to 15 If not fso.FileExists(targetfile) Then wait(2) else CompressFile = True Exit for End If Next Set fso = Nothing End Function
Call fUnzip("D:\testZip.zip","D:\testUnZip")

1 Function fUnzip(sZipFile,sTargetFolder) 2 3 'Create the Shell.Application object 4 5 Dim oShellApp:Set oShellApp = CreateObject("Shell.Application") 6 7 'Create the File System object 8 9 Dim oFSO:Set oFSO = CreateObject("Scripting.FileSystemObject") 10 11 'Create the target folder if it isn't already there 12 13 If Not oFSO.FolderExists(sTargetFolder) Then oFSO.CreateFolder sTargetFolder 14 15 'Extract the files from the zip into the folder 16 17 oShellApp.NameSpace(sTargetFolder).CopyHere oShellApp.NameSpace(sZipFile).Items 18 19 'This is a seperate process, so the script would continue even if the unzipping is not done 20 21 'To prevent this, we run a DO...LOOP once a second checking to see if the number of files 22 23 'in the target folder equals the number of files in the zipfile. If so, we continue. 24 25 Do 26 27 'WScript.Sleep 1000 28 29 Wait 1 30 31 Loop While oFSO.GetFolder(sTargetFolder).Files.Count < oShellApp.NameSpace(sZipFile).Items.Count 32 33 End Function
48、Some useful tip of QTP
Sharing some tip about QTP when i use QTP in myt work! i hope these can be useful, I urge the readers to share their experiences or tips they have used while working on QTP.
1) how to add constant number to datatable in QTP?
This is more to do with MS excel then QTP!! if you want to enter number of 1234567 to datatable,you can write it as '1234567. Just append single quotes before the number.
3)When to use a Recovery Scenario and when to use on error resume next?
Recovery Scenario is used when you can not predict at what step(s) the error can be ocurred,"On error resume next" should be used when you know if an error is expected and dont want to raise it, you may want to have different actions depending upon the error that occurred. Use err.number & err.description to get more details about the error.
4)what to do if you can not run QTP from QC?
check that you have been ticked "Allow other mercury products to run tests and components" from Tools--> Options--> Run Tab.
49、如何取到某个目录下的所以文件?
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.GetFolder("C:\")
Set fc = f.Files
For Each f1 in fc
Print f1.name
Next
50、如何检查是否ping通网络?

Function zGen_Ping(sHost) 'This function checks that you can get through to the host you require 'Example usage: ' 'Check we have internet... ' If Not zGen_Ping("www.google.com") Then ' Msgbox "Not connected to Internet",vbCritical,"Fatal Error:" ' Call ExitTest() ' End If Print "Gen_Ping : " & sHost Dim oPing, oRetStatus Set oPing = GetObject("winmgmts:").ExecQuery ("select * from Win32_PingStatus where address = '" & sHost & "'") For Each oRetStatus In oPing If IsNull(oRetStatus.StatusCode) Or oRetStatus.StatusCode <> 0 Then Print "Gen_Ping Failed - Status code :" & oRetStatus.StatusCode zGen_Ping = False Else Print "Gen_Ping OK - Bytes : " & vbTab & oRetStatus.BufferSize Print "Gen_Ping OK - Time(ms) : " & vbTab & oRetStatus.ResponseTime Print "Gen_Ping OK - TTL(s) : " & vbTab & oRetStatus.ResponseTimeToLive zGen_Ping = True End If Next Set oPing = Nothing End Function
52. 随机数
RandomNumberWithinRange = Int(((iMax - iMin) * Rnd) + iMin)
53. MaximizeIEWindow

'========================================================================== ' Name: MaximizeIEWindow ' Summary: Maximize IE window logon MPO ' Parameters: none ' Outputs: none '========================================================================== Function MaximizeIEWindow() Dim hwnd, isMaximized, isMaximizable 'Find the handle for the Browser window hwnd = Browser("CreationTime:=0").Object.HWND 'Check if the Browser is already maximized or not If Window("hwnd:=" & hwnd).GetROProperty("maximized") = True Then isMaximized = True Else isMaximized = False End If 'Check if the Browser is maximizable or not If Window("hwnd:=" & hwnd).GetROProperty("maximizable") = True Then isMaximizable = True Else isMaximizable = False End If 'Maximize the browser window if it is not already maximized and is maximizable If isMaximized = False and isMaximizable = True Then Window("hwnd:=" & hwnd).Maximize End If End Function
54. 如何在每一次新建Action时都增加一些头部说明
如果希望在每一次新建Action时都增加一些头部说明,比如作者、创建日期、说明等,则可以用Action Template来实现。方法是用记事本等文本编辑器,输入下面类似的内容:
'Company: xxxx
'Author: xxx
'Product: xxx
'Date: xx
然后将文件保存为"ActionTemplate.mst",并存放到QTP安装目录下的dat目录,重启QTP,新建的Action就会包含以上信息。
55. QTP识别浏览器IE的对象依靠的BHO Manager
什么叫BHO? BHO(Browser Helper Object),浏览器辅助对象,简称BHO, BHO是微软推出的作为浏览器对第三方程序员开放交互接口的业界标准,通过简单的代码就可以进入浏览器的领域的“交互接口”(INTERACTIVED Interface)。 BHO对象依托于浏览器主窗口。实际上,这就意味着一旦一个浏览器产生,一个新的BHO对象实例就要生成。任何BHO对象与浏览器实例的生命周期是一致的。其次,BHO仅存在于
IE4.0版本以后中。 BHO是一个COM进程内服务,注册于注册表某一键下。在启动时, IE查询那个键并把该键下的所有对象预以加载。
QTP和BHO机制是挂钩的。因为安装QTP后,每次打开IE,浏览器会自动加载BHOManager.。 而QTP在IE中识别对象也是依靠一个名为BHOManager Class的动态链接库来完成的。
所以有时候先打开IE再打开QTP,QTP不能成功读到BHOManager Class这个链接库,从而导致QTP识别对象失败。(出现正常的对象识别不了,可以先把网页和QTP都关闭。然后先启动QTP在打开被测网页)