Generation

generate functionTue, 06 Dec 2022

loop through a web page, find a list of links, and navigate to the first one

package main import ( "fmt" "net/http" "golang.org/x/net/html" "strings" ) func main() { resp,_ := http.Get("https://www.theguardian.com") defer resp.Body.Close() z := html.NewTokenizer(resp.Body) for { tt := z.Next() switch tt { case html.ErrorToken: // End of the document, we're done return case html.StartTagToken: t := z.Token() if t.Data == "a" { for _, a := range t.Attr { if a.Key == "href" && strings.Contains(a.Val, "/") { fmt.Println(a.Val) return } } } } } }

Questions about programming?Chat with your personal AI assistant