Go爬虫框架Colly:设置UA、代理、上下文传参、CSS选择器、XPath选择器、绝对路径

本文介绍使用Go语言的Colly框架进行网页抓取的方法,包括设置User-Agent、使用代理、限制域名等基本配置,以及如何通过XPath和CSS选择器提取数据。并通过两个示例演示了如何抓取多级页面数据并存入MySQL数据库。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Colly是Go的爬虫框架,简单快速,适合日常工作获取数据。

安装

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

示例1

package main

import (
	"fmt"
	"time"

	"github.com/gocolly/colly"
)

func main() {
	ua := "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36"
	c := colly.NewCollector(
		colly.UserAgent(ua),                      // 设置UA
		colly.DetectCharset(),                    // 自动编码,防止乱码
		colly.AllowedDomains("www.tcmap.com.cn"), // 限制域名
	)
	c.AllowURLRevisit = true                  // 另外一种设置方式,允许重复访问
	_ = c.SetProxy("socks://127.0.0.1:10808") // 设置代理

	// 响应内容是HTML时调用,goquerySelector来查找元素
	c.OnHTML("a[href*=\"shandong\"]", func(h *colly.HTMLElement) {
		// fmt.Println(h.Text)
		href := h.Request.AbsoluteURL(h.Attr("href")) // 绝对路径
		_ = h.Request.Visit(href)
		// 接收上下文传递过来的数据
		city := h.Response.Ctx.Get("city")
		fmt.Println(city)
	})

	_ = c.Limit(&colly.LimitRule{
		DomainGlob:  "*",
		RandomDelay: 1 * time.Second, // 延时
	})

	// 请求前调用
	c.OnRequest(func(r *colly.Request) {
		fmt.Println("访问:", r.URL)
		// 从请求往响应传递上下文数据
		r.Ctx.Put("city", "城市")
	})

	// 收到响应后调用
	c.OnResponse(func(r *colly.Response) {
		// fmt.Println(string(r.Body))
	})

	// 通过xpath来获取元素
	c.OnXML("//", func(element *colly.XMLElement) {

	})

	// 请求发生错误时调用
	c.OnError(func(r *colly.Response, err error) {
		fmt.Println(err)
	})

	c.Visit("http://www.tcmap.com.cn/shandong/")
}

示例2

package main

import (
	"fmt"
	"github.com/gocolly/colly"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"time"
)

func main() {
	dsn := "root:pass@tcp(127.0.0.1:3306)/test?charset=utf8mb4&parseTime=True&loc=Local"
	db, err := gorm.Open(mysql.New(mysql.Config{
		DSN:               dsn,
		DefaultStringSize: 256,
	}), &gorm.Config{})
	if err != nil {
		fmt.Println("连结数据库失败")
	}

	ua := "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36"
	c := colly.NewCollector(
		colly.UserAgent(ua),                      // 设置UA
		colly.DetectCharset(),                    // 自动编码,防止乱码
		colly.AllowedDomains("www.tcmap.com.cn"), // 限制域名
	)
	cityCollector := c.Clone()
	countyCollector := c.Clone()
	townCollector := c.Clone()

	// 省 http://www.tcmap.com.cn/shandong/
	c.OnHTML("#pagebody #page_left > table", func(element *colly.HTMLElement) {
		element.ForEach("tr td:first-child", func(i int, e *colly.HTMLElement) {
			city := e.ChildText("a")
			fmt.Println(city)
			relative_url := e.ChildAttr("a", "href")
			if relative_url != "" {
				absURL := e.Request.AbsoluteURL(relative_url)
				// fmt.Println(absURL)
				ctx := colly.NewContext()
				ctx.Put("city", city)
				_ = cityCollector.Request("GET", absURL, nil, ctx, nil)
			}
		})
	})

	// 市 http://www.tcmap.com.cn/shandong/jinan.html
	cityCollector.OnHTML("#pagebody #page_left > table", func(element *colly.HTMLElement) {
		city := element.Request.Ctx.Get("city")
		element.ForEach("tr td:first-child", func(i int, e *colly.HTMLElement) {
			county := e.ChildText("a")
			fmt.Println(city, county)
			relative_url := e.ChildAttr("a", "href")
			if relative_url != "" {
				absURL := e.Request.AbsoluteURL(relative_url)
				//fmt.Println(absURL)
				ctx := colly.NewContext()
				ctx.Put("city", city)
				ctx.Put("county", county)
				_ = countyCollector.Request("GET", absURL, nil, ctx, nil)
			}
		})
	})

	// 区县 http://www.tcmap.com.cn/shandong/lixiaqu.html
	countyCollector.OnHTML("#pagebody #page_left > table", func(element *colly.HTMLElement) {
		city := element.Request.Ctx.Get("city")
		county := element.Request.Ctx.Get("county")
		element.ForEach("tr td:first-child", func(i int, e *colly.HTMLElement) {
			town := e.ChildText("a")
			fmt.Println(city, county, town)
			relative_url := e.ChildAttr("a", "href")
			if relative_url != "" {
				absURL := e.Request.AbsoluteURL(relative_url)
				//fmt.Println(absURL)
				ctx := colly.NewContext()
				ctx.Put("city", city)
				ctx.Put("county", county)
				ctx.Put("town", town)
				_ = townCollector.Request("GET", absURL, nil, ctx, nil)
			}
		})
	})

	// 乡镇 http://www.tcmap.com.cn/shandong/lixiaqu_jiefanglujiedao.html
	townCollector.OnHTML("#pagebody #page_left > table", func(element *colly.HTMLElement) {
		city := element.Request.Ctx.Get("city")
		county := element.Request.Ctx.Get("county")
		town := element.Request.Ctx.Get("town")
		element.ForEach("tr td:first-child", func(i int, e *colly.HTMLElement) {
			village := e.ChildText("a")
			if village != "" {
				fmt.Println(city, county, town, village)
				_ = save(db, city, county, town, village)
			}
		})
	})

	_ = c.Limit(&colly.LimitRule{
		DomainGlob:  "*",
		RandomDelay: 1 * time.Second, // 延时
	})
	_ = c.Visit("http://www.tcmap.com.cn/shandong/")
	// c.Wait()
}

type Village struct {
	ID      uint `gorm:"primaryKey"`
	City    string
	County  string
	Town    string
	Village string
}

func (Village) TableName() string {
	return "village"
}

func save(db *gorm.DB, city string, county string, town string, village string) error {
	villageRecord := Village{City: city, County: county, Town: town, Village: village}
	db = db.Create(&villageRecord)
	db = db.Commit()
	return nil
}

参考链接

http://go-colly.org/docs/
https://pkg.go.dev/github.com/gocolly/colly

Creeper 是一个基于简单脚本( Creeper Script ,扩展名 .crs )的下一代开源爬虫框架。需要配合一门正经的编程语言(只开发了 Go 版本)来使用,先在 Creeper Script 内定义爬取规则,然后用 Go 代码来读取规则,再爬取资源。使用场景一般会用在需要同时采集大量不同网站,或者开发聚合阅读器时。(以后可能会增加 cli 和数据库访问支持)简单的用例:假如我想要爬取 HackerNews ,需要写出这样子的脚本,其实看起来有些类似 yaml 配合 jquery 的样子,但是其实差别挺大的。page(@page=1) = "https://news.ycombinator.com/news?p={@page}" news[]: page -> $("tr.athing")     title: $(".title a.storylink").text     site: $(".title span.sitestr").text     link: $(".title a.storylink").href之后在 Go 文件中来读取并使用这个脚本;package main import "github.com/wspl/creeper" func main() {     c := creeper.Open("./hacker_news.crs")     c.Array("news").Each(func(c *creeper.Creeper) {         println("title: ", c.String("title"))         println("site: ", c.String("site"))         println("link: ", c.String("link"))         println("===")     }) }执行后,将会如期地输出类似下面的内容:title:  Samsung chief Lee arrested as S.Korean corruption probe deepens site:  reuters.com link:  http://www.reuters.com/article/us-southkorea-politics-samsung-group-idUSKBN15V2RD === title:  ReactOS 0.4.4 Released site:  reactos.org link:  https://reactos.org/project-news/reactos-044-released === title:  FeFETs: How this new memory stacks up against existing non-volatile memory site:  semiengineering.com link:  http://semiengineering.com/what-are-fefets/ 标签:Creeper
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小龙在山东

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值