在这个练习中,我们将会使用 Go 的并发特性来并行化一个 Web 爬虫。
修改 Crawl 函数来并行地抓取 URL,并且保证不重复。
提示:你可以用一个 map 来缓存已经获取的 URL,但是要注意 map 本身并不是并发安全的!
解答:
package main
import (
"fmt"
"sync"
)
type Fetcher interface {
// Fetch 返回 URL 的 body 内容,并且将在这个页面上找到的 URL 放到一个 slice 中。
Fetch(url string) (body string, urls []string, err error)
}
type Cache struct {
seenUrls map[string]bool
sync.Mutex
}
func (c *Cache) Add(url string) {
c.Lock()
defer c.Unlock()
c.seenUrls[url] = true
}
func (c *Cache) Exist(url string) bool {
c.Lock()
defer c.Unlock()
_, ok := c.seenUrls[url]
return ok
}
var cache = Cache{seenUrls: make(map[string]bool)}
// Crawl 使用 fetcher 从某个 URL 开始递归的爬取页面,直到达到最大深度。
func Crawl(url string, depth int, fetcher Fetcher, end chan bool) {
// TODO: 并行的抓取 URL。
// TODO: 不重复抓取页面。
// 下面并没有实现上面两种情况:
if depth <= 0 {
end <- true
return
}
if cache.Exist(url) {
end <- true
return
}
cache.Add(url)
body, urls, err := fetcher.Fetch(url)
if err != nil {
fmt.Println(err)
end <- true
return
}
fmt.Printf("found: %s %q\n", url, body)
subCh := make(chan bool)
for _, u := range urls {
go Crawl(u, depth-1, fetcher, subCh)
}
for i := 0; i < len(urls); i++ {
<-subCh
}
end <- true
}
func main() {
end := make(chan bool)
go Crawl("https://golang.org/", 4, fetcher, end)
for {
if <-end {
return
}
}
}
// fakeFetcher 是返回若干结果的 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 是填充后的 fakeFetcher。
var fetcher = fakeFetcher{
"https://golang.org/": &fakeResult{
"The Go Programming Language",
[]string{
"https://golang.org/pkg/",
"https://golang.org/cmd/",
},
},
"https://golang.org/pkg/": &fakeResult{
"Packages",
[]string{
"https://golang.org/",
"https://golang.org/cmd/",
"https://golang.org/pkg/fmt/",
"https://golang.org/pkg/os/",
},
},
"https://golang.org/pkg/fmt/": &fakeResult{
"Package fmt",
[]string{
"https://golang.org/",
"https://golang.org/pkg/",
},
},
"https://golang.org/pkg/os/": &fakeResult{
"Package os",
[]string{
"https://golang.org/",
"https://golang.org/pkg/",
},
},
}
输出:
found: https://golang.org/ "The Go Programming Language"
not found: https://golang.org/cmd/
found: https://golang.org/pkg/ "Packages"
found: https://golang.org/pkg/os/ "Package os"
found: https://golang.org/pkg/fmt/ "Package fmt"
网友评论