Thursday, April 14, 2016

WebBrowser click html element with data-id attribute

Here's how you click an <li> element with data-id attribute. Given that the element's behavior includes navigating to another page.
VB.NET
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
If webBrowser1.Document IsNot Nothing Then
    Dim elems As HtmlElementCollection = 
webBrowser1.Document.GetElementsByTagName("li")
    For Each elem As HtmlElement In elems
        Dim nameStr As String = elem.GetAttribute("data-id")
        If ((nameStr IsNot Nothing) And (nameStr.Length <> 0)) Then
            If nameStr = "5" Then
                elem.InvokeMember("click")
            End If
        End If
    Next
End If

C#
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
if (webBrowser1.Document != null)
{
    HtmlElementCollection elems = webBrowser1.Document.GetElementsByTagName("li");
    foreach (HtmlElement elem in elems)
    {
        String nameStr = elem.GetAttribute("data-id");
        if (nameStr != null && nameStr.Length != 0)
        {
            if (nameStr == "5")
            {
                elem.InvokeMember("click"); 
            }
        }
    }
}

Test Page: Gumtree.co.za

0 comments:

Post a Comment