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

No comments:

Powered By Blogger