Golang模拟搜索引擎爬虫

最近网站需要针对百度做 SEO 优化,相关同学提交代码之后,我这边用 Go 写了个程序,模拟百度的爬虫,测试返回的内容是否正确。

其实很简单,就是发送一个请求,把百度相关的信息放入请求头中即可,代码如下:

package main

import (
    "net/http"
    "io/ioutil"
)

func main() {
    const (
        url = "https://github.com"
        userAgent = "Mozilla/5.0 (compatible; Baiduspider/2.0; +http://www.baidu.com/search/spider.html)"
    )

    // 生成client 参数为默认
    client := &http.Client{}

    // 创建请求
    req, _ := http.NewRequest("GET", url, nil)

    // 在请求头中添加指定的UA
    req.Header.Add("User-Agent", userAgent)

    // 发起请求并返回结果
    res, _ := client.Do(req)

    // 读取资源数据
    body, _ := ioutil.ReadAll(res.Body)

    // 写入文件
    ioutil.WriteFile("source.txt", body, 0644)

    res.Body.Close()
}

猜你喜欢

转载自www.cnblogs.com/liuhe688/p/10922881.html