al78310
al78310

Reputation: 75

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"?

Upvotes: 0

Views: 388

Answers (2)

al78310
al78310

Reputation: 75

Wow guys you answered me so fast, thanks a lot !!!!! You guys were totaly right, i had just to exit the loop, but I didn t know the command "exit for" Thanks guys, i learnt something !

   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
            Exit For
        End If

    Next

End Sub

Best regards, this community is awesome !

Upvotes: 0

the_lotus
the_lotus

Reputation: 12748

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.

Upvotes: 0

Related Questions