go爬蟲框架-colly實戰(二)--豆瓣top250爬取

原文連接:Hzy 博客

1.今天就嘗試用colly來爬取豆瓣Top 250!(大家都喜歡拿他來練手…)

直接上代碼了,上面有註釋。

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地址

感覺用這個框架還是挺方便的,明天在來試試爬取一些需要登錄的網站!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章