使用Golang和goquery库可轻松抓取网页标题。首先安装goquery依赖,然后通过net/http发起GET请求获取网页内容,再用goquery.NewDocumentFromReader解析HTML,利用doc.Find("title").Text()提取标题文本。示例代码展示了从https://www.php.cn/link/1536687004241eb9faeee0e227b58c60抓取标题的过程,并包含错误处理。为提高健壮性,建议设置HTTP客户端超时、添加User-Agent头以避免被屏蔽,同时检查响应状态码和Content-Type类型。该方法适用于小型爬虫或页面监控任务。

使用Golang和
goquery
goquery
<title>
首先确保你安装了
goquery
net/html
casbin/parse
go get github.com/PuerkitoBio/goquery
Golang标准库中的
net/http
goquery.NewDocumentFromReader
以下是一个完整示例,抓取指定URL的网页标题:
立即学习“go语言免费学习笔记(深入)”;
package main <p>import ( "fmt" "log" "net/http"</p><pre class='brush:php;toolbar:false;'>"github.com/PuerkitoBio/goquery"
)
func fetchTitle(url string) { // 发起HTTP GET请求 resp, err := http.Get(url) if err != nil { log.Printf("请求失败: %v", err) return } defer resp.Body.Close()
// 确保状态码是200
if resp.StatusCode != http.StatusOK {
log.Printf("HTTP错误: %d", resp.StatusCode)
return
}
// 使用goquery解析响应体
doc, err := goquery.NewDocumentFromReader(resp.Body)
if err != nil {
log.Printf("解析HTML失败: %v", err)
return
}
// 查找title标签并获取内容
title := doc.Find("title").Text()
if title == "" {
fmt.Println("未找到标题")
} else {
fmt.Printf("标题: %s\n", title)
}}
func main() { fetchTitle("https://www.php.cn/link/1536687004241eb9faeee0e227b58c60") }
实际使用中可能遇到网络超时、重定向、非UTF-8编码等问题。可以优化请求客户端来增强健壮性:
client := &http.Client{
Timeout: 10 * time.Second,
}
req, _ := http.NewRequest("GET", url, nil)
req.Header.Set("User-Agent", "Mozilla/5.0 (compatible; GoCrawler/1.0)")
<p>resp, err := client.Do(req)</p>基本上就这些。用
goquery
以上就是使用Golang和goquery库如何实现一个抓取网页标题的网络爬虫的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号