学习Go语言的第一个爬虫代码
1.第一个爬虫代码
package main
import (
"fmt"
"io/ioutil"
"net/http"
)
func main() {
//res 为结构体,储存了很多的信息
resp,err := http.Get("https://studygolang.com/pkgdoc")
if err!= nil{
fmt.Println(err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK{
fmt.Printf("Error status Code :%d",resp.StatusCode)
}
result,err := ioutil.ReadAll(resp.Body)
if err != nil{
panic(err)
}
fmt.Printf("%s",result)
}
2.对代码的简单分析
2.1Get函数
首先分析http包下的Get函数。
Get 向指定的 URL 发出 GET。 如果响应是以下重定向代码之一,则 Get 跟随重定向,最多 10 个重定向:
301 (Moved Permanently)
302 (Found)
303 (See Other)
307 (Temporary Redirect)
308 (Permanent Redirect)
如果重定向过多或存在 HTTP 协议错误,则会返回错误。 非 2xx 响应不会导致错误。 任何返回的错误都是 * url类型。 错误。 网址。 如果请求超时或被取消,错误值的 Timeout 方法将报告 true。
当 err 为 nil 时,resp 总是包含一个非 nil 的 resp.Body。 完成读取后,调用者应关闭 resp.Body。
Get 是 DefaultClient.Get 的包装器。
要使用自定义标头发出请求,请使用NewRequest和 DefaultClient.Do。
我个人的理解是:Get函数会对指定的URL发出Get请求,而我们使用resp对这个函数进行赋值后,resp的数据类型为 *http.Response。
因为使用Get函数完成读取后,应当关闭resp.Body。必须使用Colse函数进行关闭。于是有了这一行代码:defer resp.Body.Close()
Get的使用示例:
res, err := http.Get("http://www.google.com/robots.txt")
if err != nil {
log.Fatal(err)
}
robots, err := io.ReadAll(res.Body)
res.Body.Close()
if err != nil {
log.Fatal(err)
}
fmt.Printf("%s", robots)
2.2Response
使用Get函数对resp进行赋值后吗,resp的数据类型是*Response。
Response是一个结构体,中就包含很多的有关该网页信息。Response 表示来自 HTTP 请求的响应。一旦收到响应头,客户端和传输从服务器返回响应。 响应正文在读取Body字段时按需流式传输。
//Response结构体
type Response struct {
Status string
StatusCode int
Proto string
ProtoMajor int
ProtoMinor int
Header Header
Body io.ReadCloser
ContentLength int64
TransferEncoding []string
Close bool
Uncompressed bool
Trailer Header
Request *Request
TLS *tls.ConnectionState
}
2.3 StatusCode
用于判断网页访问是否成功,如果成功resp中的StatusCode值应该等于http.StatusOK(200)
2.4 最后一步
result,err := ioutil.ReadAll(resp.Body)表示使用ReadAll函数对resp中的响应体进行读取,即读取本次目标数据。
Body 代表响应体。响应正文在读取 Body 字段时按需流式传输。 如果网络连接失败或服务器终止响应,Body.Read
调用将返回错误。
读取完成后,只要对result进行输出操作就好。
3.读取结果
GOROOT=D:\CodeLife\root\GoRoot #gosetup
GOPATH=D:\ego;D:\CodeLife\Code;C:\Users\Lenovo\go

最低0.47元/天 解锁文章
4105





