Hold the CTRL key to change the window focus or perform other mouse operationsphp
二、QTP为何没法单步调试?html
安装Microsoft Script Debuger便可node
三、QTP如何访问Oracle数据库?web
Dim rs,sq,pkey
set conn=createobject("adodb.connection")
set rs=createobject("adodb.recordset")
' 须要安装Oracle客户端
conn.open "Provider=OraOLEDB.Oracle.1;Persist Security Info=False;User ID=scott;Data Source=orcl;Password=orcl;Extended Properties=;Host=192.168.1.188;Port=1521;Service Name=orcl;"
sql="SELECT * FROM TAB"
rs.open sql,conn
rs.MoveFirst
Do While rs.Eof<>true
Msgbox rs.Fields(0)
rs.MoveNext
Loop
rs.close
set rs=nothing
conn.close
set conn=nothing正则表达式
四、如何全选全部WebCheckBox对象?sql
Dim oWebChkDescshell
Set oWebChkDesc = Description.Create数据库
oWebChkDesc("micclass").value = "WebCheckBox"编程
oWebChkDesc("html tag").Value = "INPUT"windows
' 获取全部匹配描述的对象
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
QTP9.2支持的IE浏览器版本:
Microsoft Internet Explorer 6.0 Service Pack 1
Microsoft Internet Explorer 7.0
用全局的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中调用这个变量
这个变量的内存至关于共享
编辑脚本时,总感受Tab一次,移动的格数太少
Tools -> View Options
如今有一个用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
QTP的脚本在每一个action的根目录下的Script.mts文件,用UltraEdit或记事本等工具打开就能够看到。
使用反斜杠字符 ( \ )
匹配任意单个字符 ( . )
匹配列表中的任意单个字符 ( [xy] )
匹配不在列表中的任意单个字符 ( [^xy] )
匹配某个范围内的任意单个字符 ( [x-y] )
特定字符的零次或屡次匹配 ( * )
特定字符的一次或屡次匹配 ( + )
特定字符的零次或一次匹配 ( ? )
对正则表达式进行分组 ( ( ) )
匹配几个正则表达式中的一个表达式 ( | )
在一行的开始进行匹配 ( ^ )
在一行的结尾进行匹配 ( $ )
匹配包括下划线在内的任一字母数字字符 ( \w )
匹配任意非字母数字字符 ( \W )
如何判断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
hwnd = Browser("Browser").GetROProperty("hwnd")
window("hwnd:=" & hwnd).Click 12,6,micRightBtn
' Disable the Firewall
Set objFirewall = CreateObject("HNetCfg.FwMgr")
Set objPolicy = objFirewall.LocalPolicy.CurrentProfile
objPolicy.FirewallEnabled = FALSE
Set objPolicy = Nothing
Set objFirewall = Nothing
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
QTP用了一段时间菜单怎么没了呢?
重置一下Toolbars,应该就能够了
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
测试一个用户注册的功能,注册后会发送一封邮件到注册的邮箱,完了须要用户到邮箱查看,经过一个连接激活后,才算注册成功,这个功能如何用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
例如在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
下面的代码可用于停用和启用网络链接(名字可能须要根据实际的进行修改):
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
(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
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
提示错误:
[IBM][CLI Driver] SQL1042C 发生意外的系统错误。 SQLSTATE=58004
I have a problem in connecing QTP to DB2 and fetch query results.
My script goes like this: (sample POC)
connection_string = "Driver={IBM DB2 ODBC DRIVER};Database=ecomdb;Hostname=pyro.ecom.com;Port=50000;Protocol=TCPIP;Uid=admin;Pwd=adminqa;"
msgbox db_connect (curSession, connection_string)
Function db_connect( byRef curSession ,connection_string)
dim connection
on error Resume next
' Opening connection
set connection = CreateObject("ADODB.Connection")
If Err.Number <> 0 then
db_connect= "Error # " & CStr(Err.Number) & " " & Err.Description
err.clear
Exit Function
End If
connection.Open connection_string
If Err.Number <> 0 then
db_connect= "Error # " & CStr(Err.Number) & " " & Err.Description
err.clear
Exit Function
End If
set curSession=connection
db_connect=0
End Function
This script is popping up this error msg:
[IBM][CLI Driver] SQL1042C An unexpected system error occurred. SQLSTATE=58004
For the other connection string type,
data_DSN = "QAProd" 'dsn created in control panel
data_usr = "admin"
data_pwd = "adminqa"
data_alias = "ecomdb" 'name of the database
connection_string = "DSN="&data_DSN&";""UID="&data_usr&";""PWD="&data_pwd&";""DBALIAS="&data_alias&";"
i am getting same error or another error saying
password error - not able to reproduce when posting this thread
I checked connectionstrings.com and other threads in this forum discussing about QTP-DB2 connection, but couldn't find out the answer for my problem.
help me to untie this problem.
--------------------------------------------------------------------------------
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.
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
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
部分Browser方法,如Navigate、Back、Home、Refresh等在某些人的机器上是好用的,但在另一些人的机器上就很差用了。脚本执行到这些方法,并不会抛出错误;并且qtp日志里看到的状态是"done"。
通过观察发现这些机器上IE加载项(IE"工具"->"管理加载项")的不一样:
BHOManager Class插件的问题。文件名是BHOManager.dll,部分人的机器上该插件被禁用或删除掉了,猜想缘由多是使用了某些清理ie的工具致使。
解决该问题的方法很简单:
若是是被禁用了,只要从新启用便可;若是是被删除掉了,能够从新安装qtp,或者从别处拷贝BHOManager.dll文件过来,用regsvr32 BHOManager.dll注册后就能够了。
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便可看到打开文件夹已经修改成自定义的目录
用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
可利用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)
在编写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来发送字符串输入
一大堆代码要手动改为with...end with 语句来提升执行效率, 问一下QTP有没有这个功能能够自动修改呢?
Edit --> Advanced --> Apply "With" to script...
例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
参考:
http://relevantcodes.com/qtp-closing-multiple-browser-windows/
http://relevantcodes.com/qtp-working-with-multiple-browser-applications-revised/
须要对?号进行转义:
PageURL = "http://bbs.51testing.com/frame.php?frameon=yes"
Browser("version:=inter.*").Navigate PageURL
If Browser("version:=inter.*").Page("url:=http://bbs.51testing.com/frame.php\?frameon=yes").Exist Then
Print "OK"
Else
Print "NOT OK!"
End If
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)
' For I = 32 to 126
' Print I &" :" &Chr(I)
' Next
End Function
如何判断ToolbarWindow32下的按钮变灰不可用呢
If Window("XXX").WinToolbar("XXX").GetItemProperty(1,"enabled") = False Then
...
Else
...
End IF
Dim num,A(6),Redvalue
Randomize
num = 0
Redvalue = 0
While num<6
newnum = Int(20 * Rnd + 1)
iR = False
For I = 0 To num
IF A(I) = newnum Then
iR = True
End IF
Next
If iR = False Then
A(num) = newnum
num = num + 1
End If
Wend
Msgbox A(0) & " " & A(1) & " " & A(2) & " " & A(3) & " " & A(4) & " "& A(5)
测试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
Browser().Back是能够后退的,可能你的浏览器重置过
工具->Internet选项->程序->管理加载项,选择“Internet Explorer 已经使用的加载项”,查找“BHOManager Class”,在下面的“设置”中选择“启用”,重启IE就能够了。
用模拟键盘方式控制浏览器后退:
Browser("百度一下,你就知道").Page("百度一下,你就知道").WebEdit("wd").Set "QTP"
Browser("百度一下,你就知道").Page("百度一下,你就知道").WebButton("百度一下").Click
'Browser("百度一下,你就知道").Back
Wait 3
Set WshShell = CreateObject("WScript.Shell")
WshShell.SendKeys "%({LEFT})"
Set WshShell = Nothing
Msgbox GetRandomChars(10)
Function GetRandomChars( length )
Dim str
For I = 0 to length
Randomize
idx =Int( ( ub - 32 + 126 ) * Rnd +32)
str = str & Chr(idx)
Next
GetRandomChars = str
End Function
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
If VbWindow("frm_main").WinMenu("Menu").CheckItemProperty("File;Open" , "Exists" , True, 1000 ) <> True Then
Reporter.ReportEvent micPass,"找不到指定菜单项","找不到 " & Menu
Else
‘…
End If
dim time1,time2,time3
time1=TimeValue("17:32:44")
time2=TimeValue("17:32:51")
Msgbox DateDiff("s",time1,time2)
DataTable.ImportSheet "D:\XX-Project\data\Flight.xls","Resource","Global"
报错:
The DataTable.ImportSheet operation failed. File contains a feature not supported by Formula One.
QTP也不支持过高版本的Office,例如2007,即便用Office2007另存为2003格式也不支持。
dim x
x=DataTable("title","add")'将数据表中title列的当前值取出
dim conn,rst
中间为数据库链接语句。此处省略了
rst.open“select * from navigate where name=‘“ & x & ”’”,conn'此处为方便查看,将单引双引号用中文状态下书写
在x变量为正常字符串时,均可以成功查询。但当x为含有单引号的字符串,例如“i'think”。系统会报错,说语法存在问题。
"select * from navigate where name=" & Chr(39) & x & Chr(39)
or
rst.open"select * from navigate where name='" & replace(x,"'","''") & "'"
例如date返回的是2010-8-20日,如今我想要08-20-2010
msgbox DatePart("m",date)&"-"&DatePart("d",date)&"-"&DatePart("yyyy",date)
MSR.fbr是运行过程当中屏幕录像文件,若是不须要,能够删除。或者也取消生成MSR.fbr,在QTP-Tools-Options-Run中,取消勾选Save Movie to results (QTP9.2)
'===================================================================
' Name: CheckAllLinkReachable
' Summary: CheckAllLinkReachable
' Parameters:
' strBrowser: browser name
' strPage: page name
' strURLPattern: URL pattern you wan't to check. such as: ^http.*
' Return: None
'===================================================================
Function CheckAllLinkReachable(strBrowser, strPage, strURLPattern)
Dim blnReachable
blnReachable = True
Set objXML = CreateObject("Msxml2.XMLHTTP")
' Get all link on the page
Set objDes = Description.Create
objDes("micclass").Value = "Link"
Set objLinkList = Browser(strBrowser).Page(strPage).ChildObjects(objDes)
For i = 0 To objLinkList.Count() - 1
' Create XML HTTP Object
strURL = objLinkList(i).GetROProperty("href")
If RegExpTest(strURLPattern, strURL) Then
objXML.Open "POST", strURL, false
objXML.Send
' msgbox objXML.responseText
print (objLinkList(i).GetROProperty("href") & " Ready State:" & objXML.readyState & " Status: " & objXML.status)
If objXML.status <> "200" Then
blnReachable = False
End If
objXML.abort()
End If
Next
Set objXML = Nothing
CheckAllLinkReachable = blnReachable
End Function
Call fZip("D:\testZip","D:\testZip.zip")
Call fUnzip("D:\testZip.zip","D:\testUnZip")
Function fZip(sSourceFolder,sTargetZIPFile)
'This function will add all of the files in a source folder to a ZIP file
'using Windows' native folder ZIP capability.
'Returns an integer 0 if everything went ok.
Dim oShellApp, oFSO, iErr, sErrSource, sErrDescription
Set oShellApp = CreateObject("Shell.Application")
Set oFSO = CreateObject("Scripting.FileSystemObject")
'The source folder needs to have a \ on the End
If Right(sSourceFolder,1) <> "\" Then sSourceFolder = sSourceFolder & "\"
On Error Resume Next
'If a target ZIP exists already, delete it
If oFSO.FileExists(sTargetZIPFile) Then oFSO.DeleteFile sTargetZIPFile,True
iErr = Err.Number
On Error GoTo 0
If iErr <> 0 Then
fZip = iErr
Exit Function
End If
On Error Resume Next
'Write the fileheader for a blank zipfile.
oFSO.OpenTextFile(sTargetZIPFile, 2, True).Write "PK" & Chr(5) & Chr(6) & String(18, Chr(0))
iErr = Err.Number
On Error GoTo 0
If iErr <> 0 Then
fZip = iErr
Exit Function
End If
On Error Resume Next
'Start copying files into the zip from the source folder.
oShellApp.NameSpace(sTargetZIPFile).CopyHere oShellApp.NameSpace(sSourceFolder).Items
iErr = Err.Number
On Error GoTo 0
If iErr <> 0 Then
fZip = iErr
Exit Function
End If
'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.
Do Until oShellApp.NameSpace(sTargetZIPFile).Items.Count = oShellApp.NameSpace(sSourceFolder).Items.Count
'WScript.Sleep 500
Wait 1
Loop
fZip = 0
End Function
Function fUnzip(sZipFile,sTargetFolder)
'Create the Shell.Application object
Dim oShellApp:Set oShellApp = CreateObject("Shell.Application")
'Create the File System object
Dim oFSO:Set oFSO = CreateObject("Scripting.FileSystemObject")
'Create the target folder if it isn't already there
If Not oFSO.FolderExists(sTargetFolder) Then oFSO.CreateFolder sTargetFolder
'Extract the files from the zip into the folder
oShellApp.NameSpace(sTargetFolder).CopyHere oShellApp.NameSpace(sZipFile).Items
'This is a seperate process, so the script would continue even if the unzipping is not done
'To prevent this, we run a DO...LOOP once a second checking to see if the number of files
'in the target folder equals the number of files in the zipfile. If so, we continue.
Do
'WScript.Sleep 1000
Wait 1
Loop While oFSO.GetFolder(sTargetFolder).Files.Count < oShellApp.NameSpace(sZipFile).Items.Count
End Function
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.
2)how can i check ckeckpoint pass or not?
you can do so!
chk_PassFail = Browser(...).Page(...).WebEdit(...).Check (Checkpoint("Check1"))
if chk_PassFail then
MsgBox "Check Point passed"
else MsgBox "Check Point failed"
end if
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?
This is for especially for newbie!
check that you have been ticked "Allow other mercury products to run tests and components" from Tools--> Options--> Run Tab.
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.GetFolder("C:\")
Set fc = f.Files
For Each f1 in fc
Print f1.name
Next
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
1.Using a Registry Editor such as Regedt32.exe, open this key: HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\Styles
Note: If the Styles key is not present, create a new key that is called Styles.
2. Create a new DWORD value called “MaxScriptStatements” under this key and set the value to the desired number of script statements. If you are unsure of what value you need to set this to, you can set it to a DWORD value of 0xFFFFFFFF to completely avoid the dialog.
Sub IE_ChangeScriptTimeOut()
Dim Registry, sKeyPath, sValueName, dwValue, sComputer
CONST HKEY_CURRENT_USER = &H80000001
sKeyPath = "Software\Microsoft\Internet Explorer\Styles"
sValueName = "MaxScriptStatements"
dwValue = -1
sComputer = "."
On Error Resume Next
Set Registry = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" &_
sComputer & "\root\default:StdRegProv")
Registry.CreateKey HKEY_CURRENT_USER, sKeyPath
Registry.SetDWORDValue HKEY_CURRENT_USER, sKeyPath, sValueName, CLng(dwValue)
On Error Goto 0
Set Registry = Nothing
End Sub
come from http://www.cnblogs.com/davicelee/archive/2011/12/07/2278994.html#undefined