1

I am new to Golang and just started learning it. I want to find some information from a site and extract the data that I need. I am using the PuerkitoBio/goquery package to select elements and read from them. I would like to extract the data from this piece of html:

<ul class="cases-counter">
  <li>Cases: <strong>457</strong><br></li>
  <li>Active: <strong>16</strong><br></li>
</ul>

And this is the code that I have:

doc.Find(".cases-counter").Each(func(i int, s *goquery.Selection) {
    text := s.Find("li").Text()
    fmt.Print(i)
    fmt.Printf(text)
})

This prints me:

0Cases: 457Active: 16

How can I print each li element's text separately as two different variables in this example?

Leff
  • 1,968
  • 24
  • 97
  • 201

1 Answers1

0

You can try this.

func ExampleNewDocumentFromReader_string() {

    data := `
<html>
    <ul class="cases-counter">
  <li id="Cases">Cases: <strong>457</strong><br></li>
  <li id="Active">Active: <strong>16</strong><br></li>
</ul>
</html>`

    doc, err := goquery.NewDocumentFromReader(strings.NewReader(data))
    if err != nil {
        log.Fatal(err)
    }

    doc.Find(".cases-counter").Each(func(i int, s *goquery.Selection) {

        Cases := s.Find("#Cases").Text()
        Active := s.Find("#Active").Text()
        fmt.Printf("Review %d: %s, %s\n", i, Cases, Active)
    })

}
func main() {
    ExampleNewDocumentFromReader_string()
}
0example.com
  • 317
  • 2
  • 4