手摸手教你用go寫爬蟲之一(準備知識:網頁抓取)
本文介紹網頁抓取相關的知識
1. 獲取網頁內容
我們使用http.Get()
方法來獲取網頁的內容,它相當於PHP
中的file_get_contents
url := "https://hz.zu.anjuke.com/" response,err := http.Get(url)
可以看到,該方法返回了一個response
相應資訊的指標以及錯誤資訊
該響應資訊中我們要獲取的是請求體的內容,可以使用:
bytes, err := ioutil.ReadAll(response.Body) defer response.Body.Close()
注意:response.Body
必須手動呼叫Close
方法,否則該網路響應會一直佔用記憶體
原官方文件如下:
// The http Client and Transport guarantee that Body is always // non-nil, even on responses without a body or responses with // a zero-length body. It is the caller's responsibility to // close Body.
這裡我們就拿到了完整的位元組流請求的結果。
2. 完整例項
package main import ( "fmt" "io/ioutil" "net/http" ) /** 根據提供的url 獲取返回資訊內容 */ func GetContents(url string) (string ,error) { resp,err := http.Get(url) if err != nil { return "",err } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { return "", fmt.Errorf("get content failed status code is %d ",resp.StatusCode) } bytes,err := ioutil.ReadAll(resp.Body) if err != nil { return "" , nil } return string(bytes),nil } func main() { url := "https://hz.zu.anjuke.com/" contents,err := GetContents(url) if err != nil { fmt.Println(err) return } fmt.Printf(contents) }
原始碼地址:github