golang爬蟲colly 抓取豆瓣前250電影

工作中要用到一點爬蟲相關的,以前都是用python寫的,最近研究golang(主要是工作中一些API需要用golang),纔在研究,後續研究完了有可能寫個整的文章,這次用colly爬去豆瓣電影 TOP250(好像所有爬蟲入門都是用這個網站,感謝豆瓣),簡單記錄代碼如下,主要使用了colly和goquery

func TestColly(t *testing.T){
	type data struct {
		Title string `json:"title"`
		Other string `json:"other"`
		Href string `json:"href"`
		Img string `json:"img"`
	}
	var datas []data
	c := colly.NewCollector(
		)
	c.OnResponse(func(r *colly.Response) {
		dom,err:=goquery.NewDocumentFromReader(strings.NewReader(string(r.Body)))
		if err!=nil{
			fmt.Println(err)
		}
		dom.Find("ol[class=grid_view]>li").Each(func(i int, selection *goquery.Selection) {
			d:=data{}
			d.Title=selection.Find("li>div>.info>div>a>.title").First().Text()
			d.Img,_=selection.Find("li>div>.pic>a>img").Attr("src")
			d.Href,_=selection.Find("li>div>.info>.hd>a").Attr("herf")
			d.Other=selection.Find("li>div>.info>.hd>a>.other").Text()
			datas=append(datas, d)
		})
		fmt.Printf("%s",datas[1])
	})
	c.OnHTML("div.item", func(e *colly.HTMLElement) {
	})
	c.OnRequest(func(r *colly.Request) {
		r.Headers.Set("User-Agent","Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.113 Safari/537.36")
	})
	c.Visit("https://movie.douban.com/top250")
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章