Answered Help! With GetElementsByTagName("A")

Post number 14 has been selected as best answer.

vmars316

Active member
Joined
Aug 24, 2020
Messages
35
Programming Experience
Beginner
Hello & Thanks ;
The following code doesn't work , no error msg , just returns nothing .
Pls , what am I doing wrong ?
Below this Sub is the full Code :

VB.NET:
    Private Sub Target_self_Click(sender As Object, e As EventArgs) Handles Target_self.Click
        Dim linkElements As HtmlElementCollection =
WebBrowser1.Document.GetElementsByTagName("A")
        '        Dim firstLink = linkElements.Cast(Of HtmlElement).FirstOrDefault()
        If linkElements.Count > 0 Then
            Dim firstLink = linkElements.Cast(Of HtmlElement).FirstOrDefault()
            If firstLink.GetAttribute("target") = "_blank" Then
                firstLink.SetAttribute("target", "_self")
            End If
        End If
        MsgBox("Target_self_Click =  " & "Target_self_Click")
    End Sub
Here is the full pgm code :


VB.NET:
Public Class GetElementsByTagName
    Private Sub GetElementsByTagName_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        WebBrowser1.ScriptErrorsSuppressed = True
        WebBrowser1.Navigate("http://vmars.us/SafeBrowser/SafeBrowserHome.html")
    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        WebBrowser1.Navigate(txbAddress.Text)
    End Sub

    Private Sub WebBrowser1_DocumentCompleted(ByVal sender As System.Object, ByVal e As System.Windows.Forms.WebBrowserDocumentCompletedEventArgs) Handles WebBrowser1.DocumentCompleted
        Dim PageElements As HtmlElementCollection = WebBrowser1.Document.GetElementsByTagName("img")

        txbAddress.Text = WebBrowser1.Url.ToString
        For Each CurElement As HtmlElement In PageElements
            TextBox2.Text = TextBox2.Text & CurElement.GetAttribute("src") & Environment.NewLine
        Next
    End Sub

    Private Sub Target_self_Click(sender As Object, e As EventArgs) Handles Target_self.Click
        Dim linkElements As HtmlElementCollection =
WebBrowser1.Document.GetElementsByTagName("A")
        '        Dim firstLink = linkElements.Cast(Of HtmlElement).FirstOrDefault()
        If linkElements.Count > 0 Then
            Dim firstLink = linkElements.Cast(Of HtmlElement).FirstOrDefault()
            If firstLink.GetAttribute("target") = "_blank" Then
                firstLink.SetAttribute("target", "_self")
            End If
        End If
        MsgBox("Target_self_Click =  " & "Target_self_Click")
    End Sub

    Private Sub BackButton_Click(sender As Object, e As EventArgs) Handles BackButton.Click
        '        WebBrowser1.ScriptErrorsSuppressed = True
        WebBrowser1.Navigate("http://vmars.us/SafeBrowser/SafeBrowserHome.html")
    End Sub
End Class
GetElementsByTagName.png


Thanks for your Help...
 

JohnH

VB.NET Forum Moderator
Staff member
Joined
Dec 17, 2005
Messages
15,431
Location
Norway
Programming Experience
10+
You have to be more specific. What do you mean "just returns nothing", Sub methods do not have returns. Are you referring to a line of code or a return value of a statement? Why do you expect an error message? Have you debugged the code step by step and inspected the state of variables and expressions?
 

vmars316

Active member
Joined
Aug 24, 2020
Messages
35
Programming Experience
Beginner
Hi John ;
"What do you mean "just returns nothing"
When I look at the SourceCode I can see that nothing has changed .
Still lots of target="_blank" statements in there .
Also , when clicking on a link that contains target="_blank" , it opens up InternetExplorer , which is what I am trying to stop .

Any idea why the code doesn't work ?

Thanks
 

JohnH

VB.NET Forum Moderator
Staff member
Joined
Dec 17, 2005
Messages
15,431
Location
Norway
Programming Experience
10+
When I looked yesterday at the page source only the last link had target _blank, while your code only checked first link.
Any idea why the code doesn't work ?
Debug, debug, debug :)

Here's an example, put a break-point on line 26 (If firstLink...) and mouse over firstLink and expand it, look at InnerText to see which link you have captured.
Then in Immediate Window type ?firstLink.GetAttribute("target") to see what attribute value is returned.
 
Last edited:

vmars316

Active member
Joined
Aug 24, 2020
Messages
35
Programming Experience
Beginner
Thanks John;
When I hit Enter-key at image below
get this Error:
error BC30201: Expression expected.
i_view64_bTq6MGtWqq.png

??Thanks
 

vmars316

Active member
Joined
Aug 24, 2020
Messages
35
Programming Experience
Beginner
Debug is awesome! Thanks John !!
Yep , only gets 1st link
It looks like I need to For loop this statement:
linkElements As HtmlElementCollection =
WebBrowser1.Document.GetElementsByTagName("A")

But how to tell when Document.GetElementsByTagName has reached end of ("A") ?
I was assuming because it is called HtmlElementCollection and GetElements that it would auto Collect all if them .

Thanks John...
 

vmars316

Active member
Joined
Aug 24, 2020
Messages
35
Programming Experience
Beginner
John ;
I seem to be getting nowhere (see code below):
I did BreakPoint at line 28
If I enter this
firstLink.SetAttribute("target", "_self")
I get this:
Expression has been evaluated and has no value

If I enter this:
?firstLink.SetAttribute("target", "_self")
I get this:
error BC30201: Expression expected.

I added statement :
linkElements = WebBrowser1.Document.GetElementsByTagName("A")
at line 25
So I think this statement should do the trick:
If linkElements.Count > 0 Then

devenv_NsJU2ejI4H.png


Thanks
 

JohnH

VB.NET Forum Moderator
Staff member
Joined
Dec 17, 2005
Messages
15,431
Location
Norway
Programming Experience
10+
Question mark in immediate windows is to evaluate an expression; to see the value. It allows you to inspect values of objects so you can see what the state of the program is at the break point.

For example you can use it to check the attribute before and after your code has changed it. Lets say you have this code and put a break point on line 2:
VB.NET:
Dim firstLink = linkElements.Cast(Of HtmlElement).FirstOrDefault()
firstLink.SetAttribute("target", "_self")
Stop
Then in immediate windows you want to see what the value of that attribute is before that code line is executed, so you enter ?firstLink.GetAttribute("target") and see the value the link attribute has before your code is supposed to change it.
Next you press continue and debugger stops at the line that says Stop, now line 2 has executed and you want to now if the code has actually changed the attribute, so again you enter ?firstLink.GetAttribute("target") in immediate window and you can see what the value of that attribute is now.

Did you learn something when you saw the value of the atribute before and after your code changed it? Did the code change it? Was the value before the change what you thought it was?

Of course you can also add lots of Debug.WriteLine statements in your code to output values for inspecting code as it runs (and remove them afterwards), or add code to assign the expression to a variable to look at in break, but as you now know Immediate Window lets you query values with small code expression whenever you stop execution without changing the code itself. It can be very handy and time saving.
 

vmars316

Active member
Joined
Aug 24, 2020
Messages
35
Programming Experience
Beginner

vmars316

Active member
Joined
Aug 24, 2020
Messages
35
Programming Experience
Beginner
Thanks John ;
But it still disables just the First link which is:
<a href="http://..." target="_blank">American Gospel: Christ Alone (1 Hour Version) youtube</a>

Something that seems wrong is that this line :
MsgBox("linkElements.Count = " & linkElements.Count)
Yields a value of 68 .
Which is the length the statement below :
<a href="http://..." target=

Since it is a Collection , I was expecting it to show how many links that are present , which is 63 .

I also tried this: WebBrowser1.Document.querySelectAll("A") , but Error says querySelectAll( is not a member of .Document. .

Code1:

Private Sub Target_self_Click:
    Private Sub Target_self_Click(sender As Object, e As EventArgs) Handles Target_self.Click
        Dim linkElements As HtmlElementCollection =
           WebBrowser1.Document.GetElementsByTagName("A")
        Dim firstLink = linkElements.Cast(Of HtmlElement).FirstOrDefault()
        For Each link As HtmlElement In linkElements            '            linkElements = WebBrowser1.Document.GetElementsByTagName("A")
            If firstLink.GetAttribute("target") = "_blank" Then
                firstLink.SetAttribute("target", "_self")
                MsgBox("linkElements.Count =  " & linkElements.Count)
                '                   linkElements = WebBrowser1.Document.GetElementsByTagName("A")
            End If
        Next
        '        End If
        MsgBox("Target_self_Click =  " & "Target_self_Click")
    End Sub
Code2:

Public Class GetElementsByTagName:
Public Class GetElementsByTagName
    Private Sub GetElementsByTagName_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        WebBrowser1.ScriptErrorsSuppressed = True
        WebBrowser1.Navigate("http://vmars.us/reads/ListenReadWatch.html")
    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        WebBrowser1.Navigate(txbAddress.Text)
    End Sub

    Private Sub WebBrowser1_DocumentCompleted(ByVal sender As System.Object, ByVal e As System.Windows.Forms.WebBrowserDocumentCompletedEventArgs) Handles WebBrowser1.DocumentCompleted
        Dim PageElements As HtmlElementCollection = WebBrowser1.Document.GetElementsByTagName("img")

        txbAddress.Text = WebBrowser1.Url.ToString
        For Each CurElement As HtmlElement In PageElements
            TextBox2.Text = TextBox2.Text & CurElement.GetAttribute("src") & Environment.NewLine
        Next
    End Sub

    Private Sub Target_self_Click(sender As Object, e As EventArgs) Handles Target_self.Click
        Dim linkElements As HtmlElementCollection =
           WebBrowser1.Document.GetElementsByTagName("A")
        Dim firstLink = linkElements.Cast(Of HtmlElement).FirstOrDefault()
        For Each link As HtmlElement In linkElements            '            linkElements = WebBrowser1.Document.GetElementsByTagName("A")
            If firstLink.GetAttribute("target") = "_blank" Then
                firstLink.SetAttribute("target", "_self")
                MsgBox("linkElements.Count =  " & linkElements.Count)
                '                   linkElements = WebBrowser1.Document.GetElementsByTagName("A")
            End If
        Next
        '        End If
        MsgBox("Target_self_Click =  " & "Target_self_Click")
    End Sub



    Private Sub BackButton_Click(sender As Object, e As EventArgs) Handles BackButton.Click
        '        WebBrowser1.ScriptErrorsSuppressed = True
        WebBrowser1.Navigate("http://vmars.us/reads/ListenReadWatch.html")
    End Sub
End Class
Thanks for your Help...
 

JohnH

VB.NET Forum Moderator
Staff member
Joined
Dec 17, 2005
Messages
15,431
Location
Norway
Programming Experience
10+
For Each link As HtmlElement In linkElements ' linkElements = WebBrowser1.Document.GetElementsByTagName("A")
If firstLink.
What does firstLink has do with anything in your loop??? link is the loop variable.
 

vmars316

Active member
Joined
Aug 24, 2020
Messages
35
Programming Experience
Beginner
Thanks John ;
Sorry to say only the first link opens in this browser , all others open in IE 11 .
I think what's happening is that the first link is getting updated 68 times ,
so I need to tell it which one is next .
Some sort of index counter .
How would I do that .

Thanks for your Help...
 

JohnH

VB.NET Forum Moderator
Staff member
Joined
Dec 17, 2005
Messages
15,431
Location
Norway
Programming Experience
10+
I recommend that you start with tutorials to learn the basic programming elements of the language first. Let this rest until variables and loops is not a foreign concept anymore.
 

vmars316

Active member
Joined
Aug 24, 2020
Messages
35
Programming Experience
Beginner
Ok John , I'm on it !
Thanks
 

vmars316

Active member
Joined
Aug 24, 2020
Messages
35
Programming Experience
Beginner
Hi JohnH ;
Thought I would report back on my progress , here is my current code :
VB.NET:
Public Class GetElementsByTagName
    Private Sub GetElementsByTagName_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        WebBrowser1.ScriptErrorsSuppressed = True
        WebBrowser1.IsWebBrowserContextMenuEnabled = False
        Me.MinimumSize = New Size(1000, 650)
        Me.StartPosition = FormStartPosition.CenterScreen
        Me.Left = 40
        Me.Top = 20
        WebBrowser1.Navigate("http://vmars.us/SafeBrowser/SafeBrowserHome.html")
    End Sub

    Private Sub WebBrowser1_DocumentCompleted(ByVal sender As System.Object, ByVal e As System.Windows.Forms.WebBrowserDocumentCompletedEventArgs) Handles WebBrowser1.DocumentCompleted
        Dim PageElements As HtmlElementCollection = WebBrowser1.Document.GetElementsByTagName("img")
        ChangeBlankToSelf()
        txbAddress.Text = WebBrowser1.Url.ToString
    End Sub

    Private Sub ChangeBlankToSelf()
        Dim TimesThruCount = 0
        Dim linkElements As HtmlElementCollection =
               WebBrowser1.Document.GetElementsByTagName("A")
        '                Dim firstLink = linkElements.Cast(Of HtmlElement).FirstOrDefault()
        For Each link As HtmlElement In linkElements
            If link.GetAttribute("target") = "_blank" Then
                '                firstLink.SetAttribute("target", "_self")
                link.SetAttribute("target", "_self")
                EachSetLine.Text = EachSetLine.Text & ControlChars.NewLine & link.OuterHtml
            End If
            TimesThruCount = TimesThruCount + 1
        Next
    End Sub

    Private Sub Form1_ResizeEnd(sender As Object, e As EventArgs) Handles MyBase.ResizeEnd
        MsgBox("Form1 size: " & Me.Size.ToString)
    End Sub


    Private Sub BackBtn_Click(sender As Object, e As EventArgs) Handles BackBtn.Click
        WebBrowser1.GoBack()
    End Sub

    Private Sub ForwardBtn_Click(sender As Object, e As EventArgs) Handles ForwardBtn.Click
        WebBrowser1.GoForward()
    End Sub

    Private Sub RefreshBtn_Click(sender As Object, e As EventArgs) Handles RefreshBtn.Click
        WebBrowser1.Refresh()
    End Sub

    Private Sub GotoBtn_Click(sender As Object, e As EventArgs) Handles GotoBtn.Click
        WebBrowser1.Navigate(txbAddress.Text)
    End Sub

    Private Sub HomeBtn_Click(sender As Object, e As EventArgs) Handles HomeBtn.Click
        WebBrowser1.Navigate("http://vmars.us/SafeBrowser/SafeBrowserHome.html")
    End Sub
End Class
I am at a point now Where I need to Modify the registry so that program can't 'open new link in a new Tab' .
So You'll probably be hearing from me :)
Thanks for your Help...
 
Top Bottom