如何在 Go 中下载和解析 HTML 页面
此示例使用 goquery 通过 Go net/http 客户端请求 HTML 页面(https://techoverflow.net),然后使用 goquery 和简单的 CSS 样式查询选择 <title>...</title> HTML 标签并打印其内容。
go_download_parse_title.go
package main
import (
"fmt"
"log"
"net/http"
"github.com/PuerkitoBio/goquery"
)
func main() {
// 执行请求
resp, err := http.Get("https://techoverflow.net")
if err != nil {
print(err)
return
}
// 此函数结束时清理
defer resp.Body.Close()
// 读取并解析响应数据
doc, err := goquery.NewDocumentFromReader(resp.Body)
if err != nil {
log.Fatal(err)
}
// 打印 <title></title> 的内容
doc.Find("title").Each(func(i int, s *goquery.Selection) {
fmt.Printf("Title of the page: %s\n", s.Text())
})
}示例输出:
go_download_parse_output.txt
Title of the page: TechOverflowCheck out similar posts by category:
Go
If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow