如何使用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
相关产品推荐
相关产品推荐

