You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用goquery提取网页img标签alt属性作为书籍标题?

解决方案

要提取img标签的alt属性,你只需要使用goquery提供的Attr方法即可,该方法可以获取选中元素指定属性的值。

修改你代码中提取标题的部分,替换成如下代码:

title, exists := selection.Find(".image_container img").Attr("alt")
if !exists {
    title = "无标题" // 处理属性不存在的情况
}

修改后的完整代码

package main

import (
    "fmt"
    "github.com/PuerkitoBio/goquery"
    "net/http"
)

func main() {
    url := "https://books.toscrape.com"

    resp, err := http.Get(url)
    if err != nil {
        fmt.Println(err)
        return
    }
    defer resp.Body.Close()

    doc, err := goquery.NewDocumentFromReader(resp.Body)
    if err != nil {
        fmt.Println(err)
        return
    }

    doc.Find(".product_pod").Each(func(i int, selection *goquery.Selection) {
        title, exists := selection.Find(".image_container img").Attr("alt")
        if !exists {
            title = "无标题"
        }
        price := selection.Find(".price_color").Text()
        fmt.Printf("Title: %s, Price: %s\n", title, price)
    })
}

说明

  • Attr("alt")会返回两个值:属性的内容,以及一个布尔值表示该属性是否存在
  • 增加exists的判断是为了避免属性不存在时输出空值,你可以根据需求调整默认值

内容的提问来源于stack exchange,提问作者Woody

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 08:00:28