咱們在作一些自動化業務或者爬蟲業務的時候經常要用到模擬請求,例如模擬登陸,模擬購買,抓取頁面內容等。若是抓取的頁面是一個毫無權限校驗的普通頁面,那隻用Get方法便可,但現實每每比較殘酷,不是都那麼輕易的被你採集。在一個有登陸判斷的頁面,你可能要僞造cookie,header等;若是IP被限制了請求次數,你還須要使用代理IP。json
一個常規的請求以下圖:
cookie
方法代碼:post
package utils import ( "bytes" "encoding/json" "fmt" "io/ioutil" "net/http" "net/url" ) //模擬請求方法 func HttpPost(postUrl string, headers map[string]string, jsonMap map[string]interface{}, proxyIP string) (string, string) { client := &http.Client{} //轉換成postBody bytesData, err := json.Marshal(jsonMap) if err != nil { fmt.Println(err.Error()) return "", "" } postBody := bytes.NewReader(bytesData) //是否使用代理IP if proxyIP != "" { proxy := func(_ *http.Request) (*url.URL, error) { return url.Parse(proxyIP) } transport := &http.Transport{Proxy: proxy} client = &http.Client{Transport: transport} } else { client = &http.Client{} } //post請求 req, _ := http.NewRequest("POST", postUrl, postBody) for k, v := range headers { req.Header.Add(k, v) } resp, _ := client.Do(req) //返回內容 body, _ := ioutil.ReadAll(resp.Body) //解析返回的cookie var cookieStr string cookies := resp.Cookies() if cookies != nil { for _, c := range cookies { cookieStr += c.Name + "=" + c.Value + ";" } } return string(body), cookieStr }
調用代碼:url
package main import ( "encoding/json" "fmt" "goShare/utils" ) func main() { //模擬登陸 獲取cookie loginMap := make(map[string]interface{}) loginMap["name"] = "yezi" //帳號 loginMap["password"] = "123456" //密碼 body, cookiesStr := utils.HttpPost("https://www.xxx.com/login", nil, loginMap, "") //body jsonStr轉map var jmap map[string]interface{} if err := json.Unmarshal([]byte(body), &jmap); err != nil { fmt.Println("解析失敗", err) return } //判斷登陸是否成功 if jmap["code"] != "200" { fmt.Println("登陸失敗", jmap["message"]) return } //代理IP 能夠去網上找免費的或者收費的 proxyIP := "47.112.222.179:8000" //組織headers headers := make(map[string]string) headers["cookie"] = cookiesStr //抓取頁面 body2, _ := utils.HttpPost("https://www.xxx.com/detail/1", headers, nil, proxyIP) if err := json.Unmarshal([]byte(body), &jmap); err != nil { fmt.Println("解析失敗", err) return } fmt.Println("採集完畢,返回結果:", body2) }
本文只是講了一種模擬請求的場景,關於不一樣的業務能夠靈活變通一下。spa