前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >GO用内置包写爬虫

GO用内置包写爬虫

作者头像
小小咸鱼YwY
发布2020-08-20 10:28:03
3350
发布2020-08-20 10:28:03
举报
文章被收录于专栏:python-爬虫python-爬虫python-爬虫

一.要点

爬虫被想太多,把他当做一个模拟别人的请求响应即可了,所有呢go写爬虫关键是写请求

二.get请求

package main

import (
	"bytes"
	"encoding/json"
	"io"
	"io/ioutil"
	"net/http"
	"time"
)

func Get(url string) string {
	client := &http.Client{Timeout: 5 * time.Second} // 超时时间:5秒 相当于我们爬虫中的timeout参数
	resp, err := client.Get(url)   //发起请求  
    //resp, err := http.NewRequest("GET", url) 也可以这样写 post同理

    //增加header选项
    resp.Header.Add("Cookie", "xxxxxx")
    resp.Header.Add("User-Agent", "xxx")
    resp.Header.Add("X-Requested-With", "xxxx")
    //cookies就直接加在请求头中就好了
    
	if err != nil {         //请求返回的错误参数
		panic(err)
	}
	defer resp.Body.Close()  //请求成功对于请求提进行解析
	var buffer [512]byte
	result := bytes.NewBuffer(nil)
	for {
		n, err := resp.Body.Read(buffer[0:])
		result.Write(buffer[0:n])
		if err != nil && err == io.EOF {
			break
		} else if err != nil {
			panic(err)
		}
	}
	return result.String()
}


func main(){
	print(Get("http://www.baidu.com"))
}

三.post请求

//其他地方就省略咯
func Post(url string, data interface{}, contentType string) string {
	client := &http.Client{Timeout: 5 * time.Second}
	jsonStr, _ := json.Marshal(data)
	resp, err := client.Post(url, contentType, bytes.NewBuffer(jsonStr))
	if err != nil {
		panic(err)
	}
	defer resp.Body.Close()

	result, _ := ioutil.ReadAll(resp.Body)
	return string(result)
}

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2020-08-18 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 一.要点
  • 二.get请求
  • 三.post请求
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档