Certainly! Below is a simple web scraper written in Go that fetches the HTML content of a webpage and extracts specific elements using the colly package, which is a popular web scraping library in Go.
Prerequisites
- Install Go (if you haven't already).
- Install the
colly package:
go get -u github.com/gocolly/colly/v2
Go Web Scraper Code
package main
import (
"fmt"
"log"
"os"
"github.com/gocolly/colly/v2"
)
func main() {
// Create a new Colly collector
c := colly.NewCollector(
// Visit only domains matching the specified domain
colly.AllowedDomains("example.com"),
// Set a user agent to mimic a browser visit
colly.UserAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.182 Safari/537.36"),
)
// Define a callback for visiting a page
c.OnHTML("h1", func(e *colly.HTMLElement) {
fmt.Printf("Title: %s\n", e.Text)
})
c.OnHTML("a[href]", func(e *colly.HTMLElement) {
link := e.Attr("href")
text := e.Text
fmt.Printf("Link: %s -> %s\n", text, link)
})
// Handle errors during requests
c.OnError(func(r *colly.Response, err error) {
log.Printf("Request URL: %v failed with response: %v\nError: %v", r.Request.URL, r, err)
})
// URL to scrape
url := "https://example.com"
if len(os.Args) > 1 {
url = os.Args[1]
}
// Start scraping
if err := c.Visit(url); err != nil {
log.Fatalf("Failed to visit URL: %v", err)
}
}
Explanation
- Colly Collector: The
colly.NewCollector function initializes a new scraper. We set AllowedDomains to restrict scraping to a specific domain and UserAgent to mimic a browser visit.
- Callbacks:
OnHTML("h1", func(...)): Extracts and prints the text content of all <h1> elements.
OnHTML("a[href]", func(...)): Extracts and prints the text and href attributes of all anchor (<a>) tags.
- Error Handling: The
OnError callback logs any errors that occur during the request.
- URL: The scraper visits the URL provided as a command-line argument or defaults to
https://example.com.
Running the Scraper
- Save the code to a file, e.g.,
scraper.go.
- Run the scraper:
go run scraper.go https://example.com
Customization
- Modify the
OnHTML selectors to target different elements.
- Add more callbacks for different HTML elements or attributes.
- Implement additional logic to process or store the scraped data.
Let me know if you need further assistance!