Go language implementation of web crawler instances

  • 2020-05-26 09:17:14
  • OfStack

This article illustrates the web crawler method implemented by Go. Share with you for your reference. The specific analysis is as follows:

Go's concurrency feature is used here to execute web crawlers in parallel.
Modify the Crawl function to grab URLs in parallel without repeating it.

package main
import (
    "fmt"
)
type Fetcher interface {
        // Fetch return URL the body Content, and will be found on this page URL In the 1 a slice In the.
    Fetch(url string) (body string, urls []string, err error)
}
// Crawl use fetcher From a certain URL Start recursively crawling the page until the maximum depth is reached.
func Crawl(url string, depth int, fetcher Fetcher) {
        // TODO: Parallel fetching URL .
        // TODO: Do not repeatedly crawl pages.
        // The following is not the case:
    if depth <= 0 {
        return
    }
    body, urls, err := fetcher.Fetch(url)
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Printf("found: %s %q\n", url, body)
    for _, u := range urls {
        Crawl(u, depth-1, fetcher)
    }
    return
}
func main() {
    Crawl("http://golang.org/", 4, fetcher)
}
// fakeFetcher Returns several results Fetcher .
type fakeFetcher map[string]*fakeResult
type fakeResult struct {
    body string
    urls     []string
}
func (f *fakeFetcher) Fetch(url string) (string, []string, error) {
    if res, ok := (*f)[url]; ok {
        return res.body, res.urls, nil
    }
    return "", nil, fmt.Errorf("not found: %s", url)
}
// fetcher It's filled fakeFetcher .
var fetcher = &fakeFetcher{
    "http://golang.org/": &fakeResult{
        "The Go Programming Language",
        []string{
            "http://golang.org/pkg/",
            "http://golang.org/cmd/",
        },
    },
    "http://golang.org/pkg/": &fakeResult{
        "Packages",
        []string{
            "http://golang.org/",
            "http://golang.org/cmd/",
            "http://golang.org/pkg/fmt/",
            "http://golang.org/pkg/os/",
        },
    },
    "http://golang.org/pkg/fmt/": &fakeResult{
        "Package fmt",
        []string{
            "http://golang.org/",
            "http://golang.org/pkg/",
        },
    },
    "http://golang.org/pkg/os/": &fakeResult{
        "Package os",
        []string{
            "http://golang.org/",
            "http://golang.org/pkg/",
        },
    },
}

I hope this article has been helpful to your programming of Go language.


Related articles: