本文介绍网页抓取相关的知识
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