Search code examples
vb.netclassname

vb.net, webbrowser, many same classname


Yesterday I asked how to get the text in a div which has no ID.
People gave me this very good answer:

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim divs = WebBrowser1.Document.Body.GetElementsByTagName("div")
    For Each d As HtmlElement In divs
        If d.GetAttribute("className") = "js-text-container" Then
            RichTextBox1.Text = d.InnerText
        End If
    Next

But now I'm facing a new problem: I realized that many articles have the same class name "js-text-container , and when I click the button1, in my richtextbox I get the text of the LAST div with this class name...

How to get the text in the FIRST div with the class named "js-text-container"?


Solution

  • Just exit the loop after you found the first element...

    Dim divs = WebBrowser1.Document.Body.GetElementsByTagName("div")
    For Each d As HtmlElement In divs
        If d.GetAttribute("className") = "js-text-container" Then
            RichTextBox1.Text = d.InnerText
            Exit For
        End If
    Next
    

    You should learn how to use breakpoint and step the code. You would've notice this right away.