• Stars
    star
    202
  • Rank 186,809 (Top 4 %)
  • Language
    Go
  • License
    Apache License 2.0
  • Created almost 4 years ago
  • Updated about 3 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

⚡ Light weight Golang spider framework | 轻量的 Golang 爬虫框架

Gospider

gopkg goproxycn Go Test codecov

Gospider 使用文档

Gospider是一个轻量友好的的Go爬虫框架。

Gospider在管理网络请求方面使用了Goreq‌这样分割项目使功能划分更加明确,Gospider负责管理调度任务,Goreq负责处理网络请求。Gospider中的goreq.Requestgoreq.Responsegoreq.ClientGoreq提供。

🚀 Feature

  • 优雅的 API
  • 便于组织具有复杂层级和逻辑的代码
  • 友善的分布式支持
  • 一些细节 相对链接自动转换、字符编码自动解码、HTML/JSON 自动解析
  • 丰富的扩展支持 自动去重、失败重试、记录异常请求、控制延时、随机延时、并发、速率、Robots.txt 支持、随机 UA
  • 轻量 适于学习或快速开箱搭建

⚡ 网络请求

go get -u github.com/zhshch2002/goreq

Gospider依赖Goreq描述、完成网络请求,这是一个Goreq的简单演示,如需更多资料请查阅Goreq GitHub repo或者使用文档

fmt.Println(goreq.Get("https://httpbin.org/get").AddParam("A","a").Do().Txt())

结果是:

{
  "args": {
    "A": "a"
  }, 
  "headers": {
    "Accept-Encoding": "gzip", 
    "Host": "httpbin.org", 
    "User-Agent": "Go-http-client/2.0", 
    "X-Amzn-Trace-Id": "Root=1-6017ae9d-109027b5452abdd849d0161b"
  }, 
  "origin": "221.219.65.152", 
  "url": "https://httpbin.org/get?A=a"
}

此外:

  • resp.Resp() (*Response, error) 获取响应本身以及网络请求错误。
  • resp.Txt() (string, error) 自动处理完编码并解析为文本后的内容以及网络请求错误。
  • resp.HTML() (*goquery.Document, error)解析为HTML
  • resp.XML() (*xmlpath.Node, error)解析为XML
  • resp.BindXML(i interface{}) error将XML绑定到struct
  • resp.JSON() (gjson.Result, error)解析为JSON
  • resp.BindJSON(i interface{}) error将Json绑定到struct
  • resp.Error() error 网络请求错误。(正常情况下为nil

Goreq可以设置中间件、更换Http Client。请见Goreq 使用文档

⚡ 快速开始

go get -u github.com/zhshch2002/gospider

第一个例子:

package main

import (
	"github.com/zhshch2002/goreq"
	"github.com/zhshch2002/gospider"
)

func main() {
	s := gospider.NewSpider() // create spider

	s.OnResp(func(t *gospider.Task) {
		t.Println("this callback will process all response")
	})

	s.OnItem(func(t *gospider.Task, i interface{}) interface{} { // collect and save crawl result
		t.Println(i)
		return i
	})

	s.AddRootTask(
		goreq.Get("https://httpbin.org/get"),
		func(t *gospider.Task) { // this callback will only handle this request
			t.AddItem(t.Text) // submit result into OnItem pipeline
		},
	)

	s.Wait()
}

这是一个简单的爬虫,向https://httpbin.org/get发送请求并将结果作为Item存入SpiderGospider会异步处理OnItem结果,不阻塞爬虫进程。