Search code examples
vbscriptqtphp-uft

For Loop gives Object Required Error


I am comparatively new to UFT as well as VB script. I am trying to check innertext of divs inside For loop.

set getData = Browser("Browser").Page("Page").Object.getElementsByClassName("ClassName")
'Below line outputs 5'
msgbox getData.length-1
'output innertext for all these divs'
For i=0 to getData.length-1
       msgbox getData(i).innertext  
Next

This gives me Object Required Error on this line

msgbox getData(i).innertext 

My first and 2nd element is blank while 3,4,5 are non-empty values. When I write

msgbox getData(0).innertext
msgbox getData(1).innertext
msgbox getData(2).innertext

It gives me proper results

I further need to check this data against "Data" spreadsheet in UFT Any pointers would be very much helpful. Thanks,


Solution

  • Clarification needed:

    As you would like to query div text, Is that any reason to use ClassName? If that so, you could use getElementsbyTagName instead getElementsByClassName.

    However, I enhanced the code and adapting the query by any tag name option in the function. Here you go.

    Dim objResultsDictionary
    
    Set objResultsDictionary = GetTextContentFromHtmlTag(Browser("title:=Welcome: Mercury Tours").Page("title:=.*"),"div","")
    Msgbox objResultsDictionary.Count
    
    Result:8
    
    Set objResultsDictionary = GetTextContentFromHtmlTag(Browser("title:=Welcome: Mercury Tours").Page("title:=.*"),"ClassName","mouseOut")
    Msgbox objResultsDictionary.Count
    
    Result = 11
    
    Public Function GetTextContentFromHtmlTag(ByVal BrowserObject,ByVal TagName,ByVal TagValue)
        Dim objDictionary
        Dim objCollection
        Set objDictionary = CreateObject("Scripting.Dictionary")
        Select Case UCase(TagName)
            Case "DIV"
                Set objCollection = BrowserObject.Object.getElementsByTagName(TagName)
            Case "CLASSNAME"
                Set objCollection = BrowserObject.Object.getElementsByClassName(TagValue)
        End Select
        intDivCount = objCollection.Length
        If intDivCount > 0 Then
            For intCounter = 0 To intDivCount
                If IsObject(objCollection(intCounter)) Then
                    strTagInnerText = objCollection(intCounter).innerText
                    If strTagInnerText <> "" Then
                        objDictionary.Add intCounter,strTagInnerText
                    End If
                End If
            Next
        End If
        Set GetTextContentFromHtmlTag = objDictionary
    End Function
    

    What you have to do:

    You have to iterate the dictionary and get the innertext of the each tag.