Golang高效爬虫库colly

1.Colly 是一个高度可定制的抓取框架。它具有合理的默认值,并提供了许多更改它们的选项,来看基本案列

1.首先要下载colly库

go get -u github.com/gocolly/colly/

2. 基本案列

func main() {
	c := colly.NewCollector()

	// Find and visit all links
	c.OnHTML("a[href]", func(e *colly.HTMLElement) {
		e.Request.Visit(e.Attr("href"))
	})

	c.OnRequest(func(r *colly.Request) {
		fmt.Println("Visiting", r.URL)
	})

	c.Visit("http://go-colly.org/")
}

3.其中colly.colly.NewCollector()创建了一个收集器,c.Visit(“http://go-colly.org/”)是要爬取的网址,c.OnHTML是爬取html后的回调函数拿到dom节点中内容,c.OnRequest是请求之前输出请求相关信息

2.来一个爬取百度热搜的数据,网址为https://top.baidu.com/board?tab=realtime

1.查看元素

在这里插入图片描述
我们发现每个元素的class类名都一样,都是category-wrap_iQLoo horizontal_1eKyQ

c.OnHTML("div[class='category-wrap_iQLoo horizontal_1eKyQ']", func(e *colly.HTMLElement) {
	})
2.我们先获取这个里面的html,同样,我们在寻找标题的类型看看有什么规律,我们发现类名都是c-single-text-ellipsis,再看内容,发现类名也都是hot-desc_1m_jR small_Uvkd3 ellipsis_DupbZ,再看看热度都是hot-index_1Bl1a,下面开始写代码
package main

import (
	"fmt"
	"github.com/gocolly/colly"
	"github.com/gocolly/colly/debug"
	"log"
	"os"
	"strings"
)

func gethot() {
	var str string
	c := colly.NewCollector(
		colly.UserAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36 Edg/108.0.1462.54"),
		colly.Debugger(&debug.LogDebugger{}),
	)

	c.OnError(func(r *colly.Response, err error) {
		log.Println("任务出现错误-->:", err)
	})
	//爬取内容
	c.OnHTML("div[class='category-wrap_iQLoo horizontal_1eKyQ']", func(e *colly.HTMLElement) {

		str += "标题:" + e.DOM.Find(".c-single-text-ellipsis").Text() + "\t\t" + "内容:" + strings.Replace(e.DOM.Find("div[class='hot-desc_1m_jR large_nSuFU ']").Text(), " 查看更多>", "", 1) + "\t" + "热度:" + e.DOM.Find(".hot-index_1Bl1a").Text() + "\n"

	})

	err := c.Visit("https://top.baidu.com/board?tab=realtime")
	if err != nil {
		log.Println(err)
		return
	}
	c.OnRequest(func(r *colly.Request) {
		fmt.Println("请求之前回调:", r.URL.String())
	})
	fmt.Println(str)
	//写入hot.txt
	os.WriteFile("test/hot.txt", []byte(str), 0666)
}

func main() {
	gethot()
}

3.查看结果

成功了

4成功了

colly库 github.com/gocolly/colly

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值