How do I take a specific part of a string in GOLANG

Asked

Viewed 75 times

-1

I am developing a software and among its features I would like to separate a specific part of a string

My code is like this so far

baseURL := "https://google.com/" 
body, _ := ioutil.ReadAll(response.Body)
localizaScript := string(body)
fmt.Println(localizaScript)

response.Body.Close()

When I give fmt.Println(localizaScript), it returns me the huge HTML of the page in string format, I would like to get only the tag <script type="text/javascript" src="https://static.kabum.com.br/datadome.js"></script> and separate into another variable string.

  • 1

    What is the criterion for achieving this separation? Edit your question to better explain the algorithm you want to do. It would also be more ideal to try to provide a code that you have already tried to do. :-)

  • Okay, I think you’re better now heheh

  • Have you ever thought about using a library that parses HTML? An example is goquery. I believe it is the best alternative, because regular expressions are not ideas for Parsing html.

  • I’ll read about :) Thanks

1 answer

0

I believe a Web Scraper solves your problem.

Try the go get github.com/anaskhan96/soup or access https://github.com/anaskhan96/soup

package main

import (
    "fmt"
    "os"

    "github.com/anaskhan96/soup"
)

func main() {
    resp, err := soup.Get("http://g3n.rocks")
    if err != nil {
        os.Exit(1)
    }

    doc := soup.HTMLParse(resp)

    scripts := doc.FindAll("script")
    for _, script := range scripts {
        fmt.Println(script.Attrs()["src"])
        if script.Attrs()["src"] == "js/bootstrap.min.js" {
            fmt.Println("\n\n Achamos o bootstrap.min.js\n\n")
        }
    }
}

outworking:

https://www.googletagmanager.com/gtag/js?id=UA-120217498-1

js/jquery-3.3.1.min.js     
js/popper.min.js
js/bootstrap.min.js        


 Achamos o bootstrap.min.js


js/mdb.min.js

Browser other questions tagged

You are not signed in. Login or sign up in order to post.