答案:用Golang写爬虫需发送HTTP请求并解析HTML。1. 安装goquery库;2. 使用net/http发起带User-Agent的GET请求;3. 用goquery解析HTML,通过CSS选择器提取标题、段落等内容;4. 将数据保存为文件或结构化存储;5. 注意设置休眠、检查robots.txt、处理超时与重定向,动态内容需结合Chromedp。

用Golang写一个简单的爬虫抓取网站数据并不复杂,主要依赖标准库中的 net/http 发起请求,配合 goquery 或 regexp 解析HTML内容。下面是一个基础但实用的实现流程。
Go 标准库可以处理HTTP请求,但解析HTML时推荐使用第三方库 goquery(类似 jQuery 的语法):
go get github.com/PuerkitoBio/goquery
使用 net/http 发起 GET 请求,获取目标网页的响应体:
resp, err := http.Get("https://httpbin.org/html")
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
log.Fatalf("HTTP请求失败: %d", resp.StatusCode)
}注意:有些网站会设置 User-Agent 检测,建议加上请求头模拟浏览器:
立即学习“go语言免费学习笔记(深入)”;
client := &http.Client{}
req, _ := http.NewRequest("GET", "https://httpbin.org/html", nil)
req.Header.Set("User-Agent", "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)")
resp, err := client.Do(req)将响应体传给 goquery,然后用CSS选择器提取所需内容。例如抓取页面标题和段落:
doc, err := goquery.NewDocumentFromReader(resp.Body)
if err != nil {
log.Fatal(err)
}
doc.Find("h1").Each(func(i int, s *goquery.Selection) {
fmt.Printf("标题 %d: %s\n", i, s.Text())
})
doc.Find("p").Each(func(i int, s *goquery.Selection) {
fmt.Printf("段落 %d: %s\n", i, s.Text())
})可以把结果存为 JSON、CSV 或打印到控制台。例如简单输出到文件:
file, _ := os.Create("output.txt")
defer file.Close()
doc.Find("li").Each(func(i int, s *goquery.Selection) {
line := fmt.Sprintf("%d: %s\n", i, s.Text())
file.WriteString(line)
})也可以结构化存储:
type Item struct {
Title string
Desc string
}
var items []Item
doc.Find(".item").Each(func(i int, s *goquery.Selection) {
item := Item{
Title: s.Find("h3").Text(),
Desc: s.Find("p").Text(),
}
items = append(items, item)
})基本上就这些。一个轻量级爬虫的核心就是请求+解析+存储,Golang凭借其高并发特性,还能轻松扩展成多任务批量抓取。不复杂但容易忽略细节,比如编码、重试机制和错误处理。写好基础版本后,再逐步增强健壮性即可。
以上就是Golang实现简单爬虫抓取网站数据的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号