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