Certainly! Below is a simple example of using the GoColly library to scrape data from a website. In this example, we'll scrape the titles of articles from a news website's homepage.
Prerequisites
Make sure you have Go installed on your system. You can download it from the official website.
Install the GoColly package using the following command:
go get -u github.com/gocolly/colly/v2
Example Code
package main
import (
"fmt"
"github.com/gocolly/colly/v2"
"log"
)
func main() {
// Create a new collector
c := colly.NewCollector(
// Set allowed domains to prevent visiting external sites
colly.AllowedDomains("example.com"),
)
// Callback when a matched element is found
c.OnHTML("h2.entry-title a", func(e *colly.HTMLElement) {
title := e.Text
link := e.Attr("href")
fmt.Printf("Article Title: %s\nLink: %s\n\n", title, link)
})
// Callback on every request made
c.OnRequest(func(r *colly.Request) {
fmt.Println("Visiting:", r.URL.String())
})
// Callback if an error occurs
c.OnError(func(_ *colly.Response, err error) {
log.Println("Something went wrong:", err)
})
// Start the scraping
err := c.Visit("https://example.com")
if err != nil {
log.Fatalln("Failed to visit website:", err)
}
}
Explanation
-
Import Packages: The program imports necessary packages, including colly for web scraping and log for logging errors.
-
Create a Collector: We initialize a new collector using colly.NewCollector() and specify AllowedDomains to restrict the scraper to the target domain.
-
Define Callbacks:
- OnHTML: This callback is triggered when the collector matches the specified HTML element. In this case, we're targeting article titles linked within
<h2> tags (h2.entry-title a).
- OnRequest: Logs each URL the collector is about to visit.
- OnError: Captures and logs any errors that occur during the scraping process.
-
Start Scraping: We start the scraping process by calling c.Visit() with the target URL. Error handling is added to catch any issues when visiting the website.
Adjusting for a Real Website
To make this example work with a real website, we'll scrape article titles from the Hacker News homepage.
Updated Code:
package main
import (
"fmt"
"github.com/gocolly/colly/v2"
"log"
)
func main() {
c := colly.NewCollector(
colly.AllowedDomains("news.ycombinator.com"),
)
c.OnHTML("a.storylink", func(e *colly.HTMLElement) {
title := e.Text
link := e.Request.AbsoluteURL(e.Attr("href"))
fmt.Printf("Article Title: %s\nLink: %s\n\n", title, link)
})
c.OnRequest(func(r *colly.Request) {
fmt.Println("Visiting:", r.URL.String())
})
c.OnError(func(_ *colly.Response, err error) {
log.Println("Something went wrong:", err)
})
err := c.Visit("https://news.ycombinator.com/")
if err != nil {
log.Fatalln("Failed to visit website:", err)
}
}
Explanation of Changes:
-
Allowed Domains: Updated to "news.ycombinator.com" to ensure we only scrape this domain.
-
HTML Selector: Changed to "a.storylink" to match the structure of Hacker News article links.
-
Link Handling: Used e.Request.AbsoluteURL(e.Attr("href")) to get the absolute URL of the article link.
Running the Program
-
Save the Code: Copy the code into a file named main.go.
-
Run the Program:
Open your terminal and navigate to the directory containing main.go. Run:
go run main.go
-
Output:
The program will print the titles and links of the articles from the Hacker News homepage.
Visiting: https://news.ycombinator.com/
Article Title: Show HN: Open-source alternative to Adobe Illustrator
Link: https://example.com/article1
Article Title: Ask HN: Best practices for learning Go?
Link: https://example.com/article2
...
Important Considerations
-
Respect Website Policies: Always check the website's robots.txt file and terms of service to ensure you're allowed to scrape the content.
-
Be Polite: Avoid overwhelming the website with too many requests in a short period. You can throttle the request rate:
c.Limit(&colly.LimitRule{
DomainGlob: "*",
Parallelism: 2,
Delay: 2 * time.Second,
})
Remember to import the time package:
import (
"fmt"
"github.com/gocolly/colly/v2"
"log"
"time"
)
-
User-Agent: Set a custom User-Agent to identify your requests politely:
c.UserAgent = "MyScraperBot/1.0"
Additional Features
-
Error Handling: Improve error handling to make your scraper robust.
-
Data Storage: Instead of printing, store the scraped data in a file or database.
var articles []Article
type Article struct {
Title string
Link string
}
// In your OnHTML callback
articles = append(articles, Article{Title: title, Link: link})
// After scraping, save to a file or database
-
Scraping Multiple Pages: To scrape multiple pages, you can queue additional URLs.
c.OnHTML("a.morelink", func(e *colly.HTMLElement) {
nextPage := e.Request.AbsoluteURL(e.Attr("href"))
c.Visit(nextPage)
})
Conclusion
GoColly is a powerful and easy-to-use web scraping library for Go. This simple example demonstrates how to get started with scraping basic information from a website. Remember to always use web scraping responsibly and in compliance with the target website's policies.
Resources
Feel free to ask if you have any questions or need further assistance!