Keanu Lorenzo
Keanu Lorenzo

Reputation: 79

How to get the value of 'href' without id VB

I know this is a silly question but i'm having a hard time with this. I want to get the value of 'href' without an id but i can't.

Here is the HTML

<p class="CLASS">
    <a href="URL" target="TARGET">
        <img src="IMGURL" title="TITLE" border="BORDER">
    </a>
</p>

Here is what i am using(that doesn't work):

For Each WPE As HtmlElement In WebBrowser1.Document.GetElementsByTagName("a")
    If WPE.GetAttribute("target").Equals("TARGET") Then
        HREFVALUE = WPE.Getattribute("href")
        Exit For
    End If
Next

So how to get the value of 'href'?

Upvotes: 1

Views: 1508

Answers (1)

Reza Aghaei
Reza Aghaei

Reputation: 125197

You code works properly. But you didn't get expected result because you probably execute the code in an incorrect place. The code should be run after the document completed. A good place to know the document has been completed is DocumentCompleted event of the WebBrowser control:

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    Me.WebBrowser1.Navigate("d:\file.html")
End Sub
Private Sub WebBrowser1_DocumentCompleted(sender As Object, e As _
    WebBrowserDocumentCompletedEventArgs) Handles WebBrowser1.DocumentCompleted

    Dim tag = Me.WebBrowser1.Document.GetElementsByTagName("a").Cast(Of HtmlElement) _
                .Where(Function(a) a.GetAttribute("target") = "TARGET") _
                .FirstOrDefault()
    Dim href = tag.GetAttribute("href")
End Sub

I used linq in above code just for learning purpose. Your own code also works fine.

Upvotes: 1

Related Questions