Showing posts with label IE. Show all posts
Showing posts with label IE. Show all posts

Monday, September 15, 2008

Function ClickLinkByClass

During automation of web-pages I needed function that will find elements on page by specified className, that this link are placed in, and keyword (in case when there are more than one class with className or more than on link in found class). Firstly, I use function described in my prevous post - GetElementsByClassName to get list of elements with specified class, then I use keyword to find needed element or skip search if keyword was not specified. In found element I search for link by tag and then perform search in links html code by keyword, if keyword was not specified I don't perform search and take first found link in element. Fincally I click on link.
Also, if link was successfully found function returns it's value, in other case - returns False.

Code:
'This function used to click on link by indicating class of element, that contains this link
'When there are more than one element with specified class, you should specify keyword by which needed_ element can be identified (for example, ProductName for link to installer on CP)

Function ClickLinkByClass(IE, ClassName, keyword)
ClassArray = GetElementsByClassName(IE, ClassName)
If isEmpty(ClassArray) = False Then
For Each sClass in ClassArray
If keyword = "" Then
Set rightClass = sClass
Exit For
Else 'search class that contains needed keyword
If InStr(1, sClass.innerHTML, keyword, 1) <> 0 Then
Set rightClass = sClass
Exit For
End If
End If
Next
Set ElementsByTag = rightClass.getElementsByTagName("a")
If ElementsByTag.length = 0 Then
'if link was no found in element
ClickLinkByClass = False
Else
'if link was found in element of specified class
For i = 0 to ElementsByTag.Length - 1
someString = RegExp("href="".*""", rightClass.getElementsByTagName("a"_)(i).outerHTML)
If InStr(1, someString, keyword, 1) <> 0 Then
ClickLinkByClass = Mid(someString, 7, len(someString) - 7)
rightClass.getElementsByTagName("a")(i).Click
End If
Next
End If
Else
ClickLinkByClass = False
End If
End Function

Function GetElementsByClassName

Recently I faced with problem that in DOM model there is no function GetElementsByClassName like functions GetElementById or GetElementsByName, so I searched on web for this custom function and found some examples, then I modified it a bit and got such code:

'This function returns all elements found in opened IE page with specified className.
'IE - Internet Explorer object


Function GetElementsByClassName(IE, className)
ReDim Result(0)
Set tags = IE.document.all
For Each tag In tags
If tag.className = className Then
If Result(0) = Empty Then
Set Result(UBound(Result)) = tag
Else
ReDim Preserve Result(UBound(Result)+1)
Set Result(UBound(Result)) = tag
End If
End If
Next
If isEmpty(Result(0)) = False Then
GetElementsByClassName = Result
Else
GetElementsByClassName = Empty
End If
End Function
Powered By Blogger