Deprecated: imwpcache\f884414bce24ee67f\f73723ec7b1919fa5::__construct(): Implicitly marking parameter $YECBGYFECGEAFWHA as nullable is deprecated, the explicit nullable type must be used instead in /www/wwwroot/www.chuangxiangniao.com/wp-content/plugins/imwpcache-dist/build/f884414bce24ee67ff73723ec7b1919fa5.php on line 2

Deprecated: imwpcache\f884414bce24ee67f\f73723ec7b1919fa5::__construct(): Implicitly marking parameter $BBWFDDBHHYHDXXAB as nullable is deprecated, the explicit nullable type must be used instead in /www/wwwroot/www.chuangxiangniao.com/wp-content/plugins/imwpcache-dist/build/f884414bce24ee67ff73723ec7b1919fa5.php on line 2
Golang实现基础爬虫抓取网站数据_创想鸟

Golang实现基础爬虫抓取网站数据

用Golang写基础爬虫需发送HTTP请求并解析HTML。首先通过net/http库发起GET请求获取网页内容,如http.Get读取响应体;接着使用goquery库解析HTML,类似jQuery语法提取h1标题和p段落文本;最后将数据结构化为JSON输出。注意设置User-Agent、处理超时与编码,遵守robots.txt规则。完整流程包括错误处理、资源释放及数据存储,可扩展并发与反爬应对。

golang实现基础爬虫抓取网站数据

用Golang写一个基础爬虫抓取网页数据并不复杂,核心是发送HTTP请求、解析HTML内容并提取所需信息。下面是一个简单但完整的实现流程,适合初学者快速上手。

发送HTTP请求获取网页内容

Go语言标准库net/http可以轻松发起GET请求。通过http.Get获取网页响应,再读取返回的body数据。

示例代码:

resp, err := http.Get(“https://httpbin.org/html”)
if err != nil {
  log.Fatal(err)
}
defer resp.Body.Close()

body, err := io.ReadAll(resp.Body)
if err != nil {
  log.Fatal(err)
}

这里我们访问一个测试页面,实际使用时替换为目标网站URL。注意检查错误并关闭响应体,避免资源泄露。

立即学习“go语言免费学习笔记(深入)”;

解析HTML提取数据

Go没有内置的jQuery式选择器,但可以使用第三方库golang.org/x/net/html或更易用的github.com/PuerkitoBio/goquery。

使用goquery解析并提取标题和段落文本:

doc, err := goquery.NewDocumentFromReader(strings.NewReader(string(body)))
if err != nil {
  log.Fatal(err)
}

doc.Find(“h1”).Each(func(i int, s *goquery.Selection) {
  fmt.Printf(“标题: %sn”, s.Text())
})

doc.Find(“p”).Each(func(i int, s *goquery.Selection) {
  fmt.Printf(“段落: %sn”, s.Text())
})

goquery语法类似jQuery,适合习惯前端开发的用户,能快速定位元素。

处理常见问题与优化

真实爬虫会遇到反爬机制、编码问题或结构化输出需求,以下是一些实用建议:

设置User-Agent:有些网站会屏蔽默认的Go请求头,添加头信息更像浏览器行为 使用http.Client自定义超时和重试机制,避免程序卡住 对中文网站注意字符编码,必要时用golang.org/x/text/encoding转码 提取的数据可存为JSON或CSV,方便后续处理 遵守robots.txt,控制请求频率,尊重网站规则

完整示例:抓取标题和段落保存为结构体

type PageData struct {
  Title string `json:”title”`
  Content []string `json:”content”`
}

func main() {
  resp, err := http.Get(“https://httpbin.org/html”)
  if err != nil {
    log.Fatal(err)
  }
  defer resp.Body.Close()

  body, _ := io.ReadAll(resp.Body)
  doc, _ := goquery.NewDocumentFromReader(strings.NewReader(string(body)))

  data := PageData{}
  doc.Find(“h1”).First().Each(func(i int, s *goquery.Selection) {
    data.Title = s.Text()
  })

  doc.Find(“p”).Each(func(i int, s *goquery.Selection) {
    data.Content = append(data.Content, s.Text())
  })

  jsonBytes, _ := json.MarshalIndent(data, “”, ” “)
  fmt.Println(string(jsonBytes))
}

这段代码抓取页面主标题和所有段落,整理成结构化JSON输出。

基本上就这些。Golang写爬虫简洁高效,配合goroutine还能轻松实现并发抓取。关键是理解HTTP流程和HTML解析逻辑,后续可扩展代理、登录、动态渲染等功能。

以上就是Golang实现基础爬虫抓取网站数据的详细内容,更多请关注创想鸟其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1402531.html

赞 (0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
当一个Golang函数可能返回多种不同类型的错误时如何设计接口
上一篇 2025年12月15日 18:47:07
Golang微服务消息队列与事件驱动设计
下一篇 2025年12月15日 18:47:17

相关推荐

发表回复

登录后才能评论
关注微信