QTP脚本汇总比较有价值

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数据库?

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

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.

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.

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

参考:

http://relevantcodes.com/qtp-closing-multiple-browser-windows/

http://relevantcodes.com/qtp-working-with-multiple-browser-applications-revised/

32、描述性编程时,QTP 无法识别带问号的网址URL?

需要对?号进行转义:

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

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)

'   For I = 32 to 126

'          Print I &" :" &Chr(I)

'   Next

End Function

34、如何判断ToolbarWindow32下的按钮变灰不可用呢

如何判断ToolbarWindow32下的按钮变灰不可用呢

If  Window("XXX").WinToolbar("XXX").GetItemProperty(1,"enabled") = False  Then

...

Else

...

End IF

35、如何产生6个不重复的随机数?

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)

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就可以了。

用模拟键盘方式控制浏览器后退:

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

38、如何随机获得一个任意长度的字符串,主要是包含字母,数字,标点符号,常用符号等

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

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

40、WinMenu如何检查某个菜单项是否存在?

If VbWindow("frm_main").WinMenu("Menu").CheckItemProperty("File;Open" , "Exists" , True, 1000 )  <> True Then

Reporter.ReportEvent micPass,"找不到指定菜单项","找不到 " & Menu

Else

‘…

End If

41、如何获取两个时间的差?

dim time1,time2,time3

time1=TimeValue("17:32:44")

time2=TimeValue("17:32:51")

Msgbox DateDiff("s",time1,time2)

42、QTP不支持WPS的XLS文件?

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格式也不支持。

43、sql语句中动态变量中间含有单引号,查询出错

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,"'","''") & "'"

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页面链接?

  '===================================================================
  ' 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

47、如何在QTP中压缩文件?

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

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.

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.

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

51、IE8脚本错误提示脚本导致浏览器运行慢的解决办法

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

上一篇:SPSS相关和回归分析


下一篇:回归分析法&一元线性回归操作和解释