Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- func main() {
- //..http request
- // Use the html package to parse the response body from the request
- doc, err := html.Parse(resp.Body)
- if err != nil {
- fmt.Println("Error:", err)
- return
- }
- // Define a function to traverse the HTML document
- var processAllPokemon func(*html.Node)
- processAllPokemon = func(n *html.Node) {
- // Check for all <li> elements
- if n.Type == html.ElementNode && n.Data == "li" {
- // Process the details of the Pokémon within this <li> element
- processPokemonDetails(n)
- }
- // Traverse child nodes
- for c := n.FirstChild; c != nil; c = c.NextSibling {
- processAllPokemon(c)
- }
- }
- // Start processing the Pokémon details
- processAllPokemon(doc)
- }
- // Process the details of the Pokémon within the <li> element
- func processPokemonDetails(liNode *html.Node) {
- // Define a function to traverse the HTML structure within the <li> element
- var processNode func(*html.Node)
- processNode = func(n *html.Node) {
- switch n.Data {
- case "h2":
- // Extracting Pokémon name
- if n.FirstChild != nil && n.FirstChild.Type == html.TextNode {
- pokemonName := n.FirstChild.Data
- fmt.Println("Name:", pokemonName)
- }
- case "span":
- // Check for the span with class "amount"
- for _, a := range n.Attr {
- if a.Key == "class" && strings.Contains(a.Val, "amount") {
- // Print the text content of the "amount" span
- for c := n.FirstChild; c != nil; c = c.NextSibling {
- if c.Type == html.TextNode {
- fmt.Println("Price:", c.Data)
- }
- }
- }
- }
- case "img":
- // Extracting Pokémon image URL
- for _, a := range n.Attr {
- if a.Key == "src" {
- pokemonImageURL := a.Val
- fmt.Println("Image URL:", pokemonImageURL)
- }
- }
- }
- // Traverse child nodes
- for c := n.FirstChild; c != nil; c = c.NextSibling {
- processNode(c)
- }
- }
- // Start processing the nodes within the <li> element
- processNode(liNode)
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement