Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package main
- import (
- "fmt"
- "net/http"
- "strings"
- "golang.org/x/net/html"
- )
- func main() {
- //.. HTTP request
- // find all <li> elements
- var processAllPokemon func(*html.Node)
- processAllPokemon = func(n *html.Node) {
- if n.Type == html.ElementNode && n.Data == "li" {
- // process the Pokemon details within each <li> element
- processNode(n)
- }
- // traverse the child nodes
- for c := n.FirstChild; c != nil; c = c.NextSibling {
- processAllPokemon(c)
- }
- }
- // make a recursive call to your function
- processAllPokemon(doc)
- }
- // process the details of the Pokรฉmon within the <li> element
- func processNode(n *html.Node) {
- switch n.Data {
- case "h2":
- // check if FirstChild node of the h2 element is a text
- if n.FirstChild != nil && n.FirstChild.Type == html.TextNode {
- // if yes, retrieve FirstChild's data (name)
- name := n.FirstChild.Data
- // print name
- fmt.Println("Name:", name)
- }
- case "span":
- // check for the span with class "amount"
- for _, a := range n.Attr {
- if a.Key == "class" && strings.Contains(a.Val, "amount") {
- // retrieve the text content of the "amount" span
- for c := n.FirstChild; c != nil; c = c.NextSibling {
- if c.Type == html.TextNode {
- // print Pokemon price
- fmt.Println("Price:", c.Data)
- }
- }
- }
- }
- case "img":
- // check for the src attribute in the img tag
- for _, a := range n.Attr {
- if a.Key == "src" {
- // retrieve src value
- ImageURL := a.Val
- // print image URL
- fmt.Println("Image URL:", ImageURL)
- }
- }
- }
- // Traverse child nodes
- for c := n.FirstChild; c != nil; c = c.NextSibling {
- processNode(c)
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement