To scrape the head of a webpage with Go, you can use the net/http package to fetch the page and a parsing library like golang.org/x/net/html to extract the head section. Here's how to do it:
package main
import (
"fmt"
"net/http"
"strings"
"golang.org/x/net/html"
)
func getHeadContent(url string) (string, error) {
// Fetch the webpage
resp, err := http.Get(url)
if err != nil {
return "", err
}
defer resp.Body.Close()
// Parse the HTML
doc, err := html.Parse(resp.Body)
if err != nil {
return "", err
}
// Find the head element
var headContent string
var findHead func(*html.Node)
findHead = func(n *html.Node) {
if n.Type == html.ElementNode && n.Data == "head" {
// Extract the inner HTML of the head element
var b strings.Builder
for c := n.FirstChild; c != nil; c = c.NextSibling {
html.Render(&b, c)
}
headContent = b.String()
return
}
// Recursively search children
for c := n.FirstChild; c != nil; c = c.NextSibling {
findHead(c)
}
}
findHead(doc)
return headContent, nil
}
func main() {
url := "https://example.com"
head, err := getHeadContent(url)
if err != nil {
fmt.Printf("Error: %v\n", err)
return
}
fmt.Println("Head content:")
fmt.Println(head)
}
For more control and easier parsing, you might want to use a higher-level library like goquery, which provides jQuery-like syntax:
package main
import (
"fmt"
"log"
"github.com/PuerkitoBio/goquery"
)
func main() {
url := "https://example.com"
// Load the HTML document
doc, err := goquery.NewDocument(url)
if err != nil {
log.Fatal(err)
}
// Find and print each element in the head
doc.Find("head").Each(func(i int, s *goquery.Selection) {
// Get the entire head HTML
headHtml, _ := s.Html()
fmt.Println("Head content:", headHtml)
// Or extract specific elements
s.Find("title").Each(func(i int, title *goquery.Selection) {
fmt.Println("Title:", title.Text())
})
s.Find("meta").Each(func(i int, meta *goquery.Selection) {
name, _ := meta.Attr("name")
content, _ := meta.Attr("content")
if name != "" {
fmt.Printf("Meta %s: %s\n", name, content)
}
})
})
}
To use goquery, install it first:
go get github.com/PuerkitoBio/goquery
Both approaches will effectively scrape the head section of a webpage. The first method gives you more low-level control using the standard library, while goquery provides a more convenient API for HTML manipulation and is particularly useful if you need to extract specific elements or attributes from the head section.