Advertisement
dereksir

Untitled

Dec 29th, 2023
204
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Go 1.67 KB | None | 0 0
  1. package main
  2.  
  3. import (
  4.     "fmt"
  5.     "net/http"
  6.     "strings"
  7.  
  8.     "golang.org/x/net/html"
  9. )
  10.  
  11. func main() {
  12.     //.. HTTP request
  13.  
  14.     // find all <li> elements
  15.     var processAllPokemon func(*html.Node)
  16.     processAllPokemon = func(n *html.Node) {
  17.         if n.Type == html.ElementNode && n.Data == "li" {
  18.             // process the Pokemon details within each <li> element
  19.             processNode(n)
  20.  
  21.         }
  22.         // traverse the child nodes
  23.         for c := n.FirstChild; c != nil; c = c.NextSibling {
  24.             processAllPokemon(c)
  25.         }
  26.     }
  27.     // make a recursive call to your function
  28.     processAllPokemon(doc)
  29. }
  30.  
  31. // process the details of the Pokémon within the <li> element
  32. func processNode(n *html.Node) {
  33.     switch n.Data {
  34.     case "h2":
  35.         // check if FirstChild node of the h2 element is a text
  36.         if n.FirstChild != nil && n.FirstChild.Type == html.TextNode {
  37.             // if yes, retrieve FirstChild's data (name)
  38.             name := n.FirstChild.Data
  39.             // print name
  40.             fmt.Println("Name:", name)
  41.         }
  42.  
  43.     case "span":
  44.         // check for the span with class "amount"
  45.         for _, a := range n.Attr {
  46.             if a.Key == "class" && strings.Contains(a.Val, "amount") {
  47.                 // retrieve the text content of the "amount" span
  48.                 for c := n.FirstChild; c != nil; c = c.NextSibling {
  49.                     if c.Type == html.TextNode {
  50.                         // print Pokemon price
  51.                         fmt.Println("Price:", c.Data)
  52.                     }
  53.                 }
  54.             }
  55.         }
  56.  
  57.     case "img":
  58.         // check for the src attribute in the img tag
  59.         for _, a := range n.Attr {
  60.             if a.Key == "src" {
  61.                 // retrieve src value
  62.                 ImageURL := a.Val
  63.                 // print image URL
  64.                 fmt.Println("Image URL:", ImageURL)
  65.             }
  66.         }
  67.     }
  68.  
  69.     // Traverse child nodes
  70.     for c := n.FirstChild; c != nil; c = c.NextSibling {
  71.         processNode(c)
  72.     }
  73. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement