golang爬虫colly 发送post请求

来自:网络
时间:2023-01-01
阅读:

继续还是工作中使用colly,不管是官网,还是网上的一些文章(其实90%就是把官网的案例抄过去),都是一样的格式,没有讲到post,测试了几次,记录一下post的使用

    c := colly.NewCollector()
    type data struct {
        Phone string `json:"phone" binding:"required"`
    }
    d:=&data{
        Phone:"18190897361",
    }
    da,err:=json.Marshal(d)

    if err!=nil{
        fmt.Println(err)
    }
    c.OnResponse(func(response *colly.Response) {
        fmt.Println(string(response.Body))
    })
    c.OnRequest(func(r *colly.Request) {
        fmt.Println(r)
        fmt.Println(r.Method)
        r.Headers.Set("Content-Type", "application/json;charset=UTF-8")
        r.Headers.Set("User-Agent","Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.113 Safari/537.36")
    })
    c.OnError(func(response *colly.Response, e error) {
        fmt.Println(e)
    })
    c.PostRaw("http://www.××××.com:×××/baseDevice/getUserInfo",da)
    //c.Visit("http://www.××××.com:×××/baseDevice/getUserInfo")

其实也没多少不一样,首先准备你要发送的json格式的数据(现在90%都是json格式请求了),

type data struct {
        Phone string `json:"phone" binding:"required"`
    }
    d:=&data{
        Phone:"18190897361",
    }
    da,err:=json.Marshal(d)

这里只发送一个电话号码,第二部就是最后的发送了

c.PostRaw("http://www.××××.com:×××/baseDevice/getUserInfo",da)

1:这句话一定要写到最后

c.Visit(“http://www.××××.com:×××/baseDevice/getUserInfo”)

Visit方法,点进去源码可以看到默认走的是get模式,我们这里发送post,就不需要写了
就这么简单—结束

返回顶部
顶部