首页 > 架构设计 > 数据架构 > Golang 网络爬虫框架gocolly/colly
是 Golang 实现的网络爬虫框架,名列 go 版爬虫程序榜首。
go get -u github.com/gocolly/colly/...
import ( "fmt" "github.com/gocolly/colly")func main() { c := colly.NewCollector() c.OnResponse(func(r *colly.Response) { fmt.Println("IP:", string(r.Body)) }) //c.SetProxy(") c.Visit(")}
SetProxy 函数可以用来配置 HTTP 代理。
colly 的主体是 Collector 对象,管理网络通信和负责在作业运行时执行附加的回掉函数。使用 colly 需要先初始化 Collector :
c := colly.NewCollector()
vgo 是 Go 语言推出的第三方库管理工具,在 Go 语言新版本中使用。
· go help mod 查看帮助。
· go mod init < 项目模块名称 > 初始化模块,会在项目根目录下生成 go.mod 文件,是可以自己手动编辑的。
依赖包大多在 Github 上,安装依赖可能会出现连接超时等问题,可以配置全局 git 代理:
git config --global http.proxy config --global https.proxy 取消代理: git config --global --unset http.proxygit config --global --unset https.proxy
cmd 走 shadowsocks 代理:
set http_proxy=127.0.0.1:1080set https_proxy=127.0.0.1:1080curl cip.ccIP : 140.206.97.42 地址 : 中国 上海数据二 : 上海市 | 联通 URL :
Linux 使用 export 设置环境变量,代码同上。
1. OnRequest 在发起请求前被调用。
2. OnError 请求过程中如果发生错误被调用。
3. OnResponse 收到回复后被调用。
4. OnHTML 在 OnResponse 之后被调用,如果收到的内容是 HTML 。
5. OnScraped 在 OnHTML 之后被调用。
官方提供的 代码:
package mainimport ( "fmt" "github.com/gocolly/colly")func main() { // Instantiate default collector c := colly.NewCollector( // Visit only domains: hackerspaces.org, wiki.hackerspaces.org colly.AllowedDomains("hackerspaces.org", "wiki.hackerspaces.org"), ) // On every a element which has href attribute call callback c.OnHTML("a[href]", func(e *colly.HTMLElement) { link := e.Attr("href") // Print link fmt.Printf("Link found: %q -> %s\n", e.Text, link) // Visit link found on page // Only those links are visited which are in AllowedDomains c.Visit(e.Request.AbsoluteURL(link)) }) // Before making a request print "Visiting ..." c.OnRequest(func(r *colly.Request) { fmt.Println("Visiting", r.URL.String()) }) // Start scraping on c.Visit(")}
该实例程序仅访问 hackerspaces.org 域内的链接, OnHTML 回掉函数的选择器为 a[href] ,选择页面内具有 href 属性的 a 类型元素,找到链接后继续抓取。 运行的部分结果如下:
Visiting found: "navigation" -> #column-oneLink found: "search" -> #searchInputLink found: "" -> /File:Cbase07.jpgVisiting found: "navigation" -> #column-oneLink found: "search" -> #searchInputLink found: "File" -> #fileLink found: "File history" -> #filehistoryLink found: "File usage" -> #filelinksLink found: "" -> /images/e/ec/Cbase07.jpgVisiting https://hackerspaces.org/images/e/ec/Cbase07.jpgLink found: "800 × 600 pixels" -> /images/thumb/e/ec/Cbase07.jpg/800px-Cbase07.jpgVisiting https://hackerspaces.org/images/thumb/e/ec/Cbase07.jpg/800px-Cbase07.jpg
本文转载自:
来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/31555707/viewspace-2558361/,如需转载,请注明出处,否则将追究法律责任。