工作中要用到一点爬虫相关的,以前都是用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")
}