HelpFind Element In Webbrowser Based On Src

Posts 1–2 of 2 · Page 1 of 1
Find Element In Webbrowser Based On Src
Hey, so again i have one of my many webbrowser control questions. This time the question is, if i have a webpage source code that looks like such:
Code:
<img src="<img url>" width="62" height="20" alt="LIKE">
and i want to invoke the element based on the image url, how can i do this?
I tried:
Code:
For Each ele As HtmlElement In LikeBrowser.Document.All
            If ele.GetAttribute("src") = "<image url>" Then
                ele.InvokeMember("click")
            End If
        Next
however, it never executes the "ele.InvokeMember("click")" statement (i tested that via putting a message box in there). I'd use the alt, but letter in the webpage there's an element with the same alt, so it invokes both & the other element causes a popup. I also tried using:
Code:
For Each ele As HtmlElement In LikeBrowser.Document.All
            If ele.GetAttribute("alt") = "LIKE" and ele.GetAttribute("width") = "62" Then
                ele.InvokeMember("click")
            End If
        Next
but that gives the same result as using the src (it doesn't ever execute).

Can anyone help?
This work just fine for me then:

Code:
Dim img As HtmlElement = WebBrowser1.Document.GetElementsByTagName("img").Cast(Of HtmlElement).FirstOrDefault( _
    Function(h) h.GetAttribute("src").ToLower().Equals("http://example.com/images/logo.png") _
)

If img IsNot Nothing Then
     ' found
Else
     ' not found
End If
Obviously you'll need to change the url (and make sure it's lowercase). Otherwise you can use this more generic definition:

Code:
Public Shared Function GetElementsByCriteria(ByVal html As HtmlDocument, ByVal criteria As Func(Of HtmlElement, Boolean), Optional ByVal tag As String = "") As IEnumerable(Of HtmlElement)
	Dim collection As HtmlElementCollection = CType(If(String.IsNullOrEmpty(tag), html.All, html.GetElementsByTagName(tag)), HtmlElementCollection)
	Return collection.Cast(Of HtmlElement)().Where( _
		Function(e) criteria.Invoke(e) _
	)
End Function
And then use it like this:
Code:
Dim imgs As IEnumerable(Of HtmlElement) = GetElementsByCriteria(WebBrowser1.Document, Function(h) h.GetAttribute("src").ToLower().Equals("http://example.com/images/logo.png"), "img")
For Each i As HtmlElement in imgs
    ' do something with the HtmlElement "i"
Next i
Posts 1–2 of 2 · Page 1 of 1

Post a Reply

Similar Threads

Tags for this Thread

None

Talk with us