golang爬虫必备之发起Http请求及添加相关参数

    golang想要爬取网站还是很简单的,只要利用官网给的net/http包中的client提供的方法实现。刚开始的时候是分不清其包的用法,今天来好好的总结一下的:


1.Get请求

    直接使用http.Get的请求方式,就可以获取页面的信息,需要注意的是每次用完以后需要close的操作

package main

import (
   "net/http"
   "fmt"
   "io/ioutil"
)

func main() {
   resp, err := http.Get("https://www.json.cn/")
   if err != nil {
      panic(err)
   }
   defer resp.Body.Close()
   body, err := ioutil.ReadAll(resp.Body)
   fmt.Println(string(body))
}

2.post请求

    这里面有两种post请求,分别是单个参数和多个参数的版本

2.1post单个参数

    引用包Api说明:Post向指定的URL发出一个POST请求。bodyType为POST数据的类型, body为POST数据,作为请求的主体。如果参数body实现了io.Closer接口,它会在发送请求后被关闭。调用者有责任在读取完返回值resp的主体后关闭它。

    POST数据的类型一般会设为"application/x-www-form-urlencoded"

package main

import (
   "net/http"
   "fmt"
   "io/ioutil"
   "strings"
)

func main() {
   resp, err := http.Post("http://1.dev.wanguo.net/seller/login", "application/x-www-form-urlencoded", strings.NewReader("mobile=111"))
   if err != nil {
      fmt.Println(err)
   }
   defer resp.Body.Close()
   body, err := ioutil.ReadAll(resp.Body)
   if err != nil {
      // handle error
   }

   fmt.Println(string(body))
}

2.2post多个参数

package main

import (
   "net/http"
   "fmt"
   "io/ioutil"
   "net/url"
)

func main() {
   resp, err := http.PostForm("http://1.dev.wanguo.net/seller/login", url.Values{"mobile": {"111"}, "pwd": {"123"}})
   if err != nil {
      fmt.Println(err)
   }
   defer resp.Body.Close()
   body, err := ioutil.ReadAll(resp.Body)
   if err != nil {
      // handle error
   }

   fmt.Println(string(body))
}

3.复杂的请求

如果爬取页面中需要登陆(cookie),携带参数等需求,那么就需要利用到Http.client

    

    3.1GET

package main

import (
   "net/http"
   "fmt"
   "io/ioutil"
)

func main() {
   client := &http.Client{}
   //读取Api数据
   url:="http://kq.ngking.com:8080/iclock/staff/transaction/?p=1&t=staff_transaction.html&UserID__id__exact=XXX&fromTime=&toTime="
   req, err := http.NewRequest("GET", url, nil)
   if err != nil {
      panic(err)
   }
   req.Header.Add("Cookie","sessionid=5edb1f18c5a0cb334b42b2383c899e01")
   resp, err := client.Do(req)

   defer resp.Body.Close()

   body, _ := ioutil.ReadAll(resp.Body)
   fmt.Println(string(body))

}

    3.2POST

func getcookie() (cookie string){
   client := &http.Client{}
   post_arg := url.Values{"username": {"2300"}, "password": {"2300"}}
   //读取Api数据
   urls := "http://kq.ngking.com:8080/iclock/accounts/login/"
   fmt.Println(post_arg.Encode())
   req, err := http.NewRequest("POST", urls, strings.NewReader(post_arg.Encode()))
   if err != nil {
      panic(err)
   }
   resp, err := client.Do(req)
   //获取cookie后并转化成string
   cookie=resp.Cookies()[0].Value
   return
}

文中的例子是get请求,如用post,同上面的post请求,必须要设定Content-Type为application/x-www-form-urlencoded,post参数才可正常传递。

扫描二维码关注公众号,回复: 2393845 查看本文章


猜你喜欢

转载自blog.csdn.net/feiwutudou/article/details/80965798
今日推荐