grequests

Status
Done
Assign
Date
Apr 10, 2023
我们在使用Go做爬虫的时候,首先接触的肯定是 Golang 标准库 net/http
https://pkg.go.dev/net/http 有兴趣的可以去看看文档。 但是老实说 这个库个人感觉不是特别的好用
有可能是之前就是使用了Python 所以还是感觉如果有像Python库中的requests 那样去实现请求就好了。 所以GoRequests 就诞生了。

官方文档

  • 响应可以序列化为 JSON 和 XML
  • 轻松上传文件
  • 轻松下载文件
  • 支持以下 HTTP 谓词GET, HEAD, POST, PUT, DELETE, PATCH, OPTIONS

安装

go get -u github.com/levigross/grequests

导入

import "github.com/levigross/grequests"

发送请求

Get请求

ro := &RequestOptions{ Params: map[string]string{"name": "hybpjx"}, } // url路径上的参数会被覆盖 resp, err := grequests.Get("<http://httpbin.org/get?h=1>", ro) if err != nil { panic(err) } fmt.Println(resp.String())

Post请求

option := &grequests.RequestOptions{Data: map[string]string{"url": "<https://www.cnblogs.com/zichliang/p/17302343.html>"}} resp, err := grequests.Post("<http://httpbin.org/post>", option) if err != nil { panic(err) } if resp.Ok != true { fmt.Println(resp.Ok) }

Post上传文件

还可以支持上传文件
// 允许您通过指定磁盘上的位置来创建FileUpload结构片 fd, err := grequests.FileUploadFromDisk("test/1") if err != nil { fmt.Printf("文件打开失败:%v\\n", err) } // 这将以请求的形式上传文件 resp, _ := grequests.Post("<http://httpbin.org/post>", &grequests.RequestOptions{ Files: fd, Data: map[string]string{"One": "Two"}, }) fmt.Println(resp.Ok,resp.StatusCode)

Gorequests 使用session

session := grequests.Session{ RequestOptions: &grequests.RequestOptions{ Headers: map[string]string{ "authority": "mp3.haoge500.com", "referer": "<https://www.zz123.com/>", "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36", }, }, }

GoRequests 使用代理

gorequest代理,非常简单 网上的Demo很多 也不只这一个 我展示的是阿布云的代理 需要注意的是 需要把 Proxies 中的url 添加为 *url.URL 代理
package test import ( "fmt" "github.com/levigross/grequests" "net/url" "testing" "time" ) // 代理服务器 const proxyServer = "http-pro.xxx.com:9010" // 代理隧道验证信息 const proxyUser = "xxxxxxxxx" const proxyPass = "xxxxxxxxx" type Proxy struct { AppID string AppSecret string } func (p Proxy) ProxyURL() *url.URL { proxyUrl, _ := url.Parse("http://" + p.AppID + ":" + p.AppSecret + "@" + proxyServer) return proxyUrl } func TestCommon(t *testing.T) { // 初始化 proxy http client proxyURL := Proxy{AppID: proxyUser, AppSecret: proxyPass}.ProxyURL() fmt.Println(proxyURL) trueUrl := "<http://www.xiushui.gov.cn/xxgk/bmxxgk/sthjj/sthj/xmhp/index.html>" ro := &grequests.RequestOptions{ Headers: map[string]string{ "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36", }, Proxies: map[string]*url.URL{ "http": proxyURL, }, } resp, err := grequests.Get(trueUrl, ro) if err != nil { panic(err.Error()) } fmt.Println("", resp.StatusCode) time.Sleep(time.Second * 10) }