Wednesday, August 19, 2009

QTP Script to Count Elements on a Webpage



I have used www.google.com on Firefox 3.0.13 for this script (See above screenshot). Make sure google.com is open in Firefox. Write the below script in a new test in QTP and run it.

L=0
W=0
m=0
WB=0
Set oDesc = Description.Create()
'You can use the ChildObjects method to retrieve all objects located inside a
'specified parent object, or only those child objects that fit a certain programmatic description.
Set rc = Browser("name:=Google").Page("title:=Google").ChildObjects(oDesc)
num = rc.Count()

For i=0 to num-1
'checking whether the object is a Link or Image etc.
var = rc(i).GetTOProperty("Class Name")
Select Case var
Case "Link"
L=L+1
var2 = rc(i).GetROProperty("text")
c=c & var2 & vbcrlf
Case "Image"
m=m+1
var1 = rc(i).GetROProperty("src")
b=b & var1 & vbcrlf
Case "WebElement"
W=W+1
Case "WebButton"
WB=WB+1
Case Else
End Select
Next
msgbox "Links "& L & vbcrlf &"Images "& m & vbcrlf & "WebElements " & W & vbcrlf & "WebButtons " & WB
msgbox b
msgbox c

The line with ChildObjects method in the script retrieves all the objects on this google page. And from all the retrieved objects, you can find out whether the object is a Link or Image etc. Furthermore you can retrieve different properties of those retrieved objects. The above script when run shows these below message boxes. The first message box contains objects and their count. The second contains the path of the retrieved images. In this case it shows only 1 path as only 1 image was retrieved. In the next message box it shows value of “text” property for all the links retrieved. In this way you can modify the script according to your requirements.