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")
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值