原文连接:Hzy 博客
1.今天就尝试用colly来爬取豆瓣Top 250!(大家都喜欢拿他来练手..)
直接上代码了,上面有注释。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
package main
import (
"fmt"
"github.com/PuerkitoBio/goquery"
"github.com/gocolly/colly"
"github.com/gocolly/colly/extensions"
"regexp"
"strings"
"time"
)
func main() {
t := time.Now()
number := 1
c := colly.NewCollector(func(c *colly.Collector) {
extensions.RandomUserAgent(c) // 设置随机头
c.Async=true
},
//过滤url,去除不是https://movie.douban.com/top250?start=0&filter= 的url
colly.URLFilters(
regexp.MustCompile("^(https://movie\\.douban\\.com/top250)\\?start=[0-9].*&filter="),
),
) // 创建收集器
// 响应的格式为HTML,提取页面中的链接
c.OnHTML("a[href]", func(e *colly.HTMLElement) {
link := e.Attr("href")
//fmt.Printf("find link: %s\n", e.Request.AbsoluteURL(link))
c.Visit(e.Request.AbsoluteURL(link))
})
// 获取电影信息
c.OnHTML("div.info", func(e *colly.HTMLElement) {
e.DOM.Each(func(i int, selection *goquery.Selection) {
movies := selection.Find("span.title").First().Text()
director := strings.Join(strings.Fields(selection.Find("div.bd p").First().Text()), " ")
quote := selection.Find("p.quote span.inq").Text()
fmt.Printf("%d --> %s:%s %s\n", number, movies, director, quote)
number += 1
})
})
c.OnError(func(response *colly.Response, err error) {
fmt.Println(err)
})
c.Visit("https://movie.douban.com/top250?start=0&filter=")
c.Wait()
fmt.Printf("花费时间:%s",time.Since(t))
}
github地址:github地址