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
- // Create an HTML tokenizer
- z := html.NewTokenizer(resp.Body)
- // Loop through HTML tokens
- for {
- tokenType := z.Next()
- switch tokenType {
- case html.StartTagToken, html.SelfClosingTagToken:
- token := z.Token()
- // Check for all <li> element
- if token.Data == "li" {
- // Process the details of the Pokémon within this <li> element
- processPokemonDetails(z)
- // Exit the loop after processing the details
- //return
- }
- }
- if tokenType == html.ErrorToken {
- break
- }
- }
- }
- func processPokemonDetails(z *html.Tokenizer) {
- // parse Tokens for Relevant Data within the <li> element
- for {
- tokenType := z.Next()
- switch tokenType {
- case html.StartTagToken, html.SelfClosingTagToken:
- token := z.Token()
- // parse Tokens for Relevant Data
- switch token.Data {
- case "h2":
- // Extracting Pokémon name
- tokenType = z.Next()
- if tokenType == html.TextToken {
- name := z.Token().Data
- fmt.Println("Name:", name)
- }
- case "span":
- // check for the span with class "price"
- hasPriceClass := false
- for _, attr := range token.Attr {
- if attr.Key == "class" && strings.Contains(attr.Val, "price") {
- hasPriceClass = true
- break
- }
- }
- // ...
- if hasPriceClass {
- tokenType = z.Next()
- // check if the next token is a span with class "amount"
- if tokenType == html.StartTagToken || tokenType == html.SelfClosingTagToken {
- nextToken := z.Token()
- if nextToken.Data == "span" {
- amountClass := false
- for _, attr := range nextToken.Attr {
- if attr.Key == "class" && strings.Contains(attr.Val, "amount") {
- amountClass = true
- break
- }
- }
- // if the next span has class "amount," loop through and print its text content
- if amountClass {
- var currencySymbol, priceValue string
- for {
- tokenType = z.Next()
- if tokenType == html.TextToken {
- currencySymbol = z.Token().Data
- }
- tokenType = z.Next()
- if tokenType == html.TextToken {
- priceValue = z.Token().Data
- } else if tokenType == html.EndTagToken && z.Token().Data == "span" {
- break
- }
- }
- amount := currencySymbol + priceValue
- fmt.Println("Price:", amount)
- }
- }
- }
- }
- case "img":
- // check for the src attribute and retrieve its value
- for _, attr := range token.Attr {
- if attr.Key == "src" {
- imageURL := attr.Val
- fmt.Println("Image URL:", imageURL)
- }
- }
- }
- }
- if tokenType == html.ErrorToken {
- break
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement