如何在Go语言中获取属性href值的值 [英] how to get value of attribute href value in Go language

查看:93
本文介绍了如何在Go语言中获取属性href值的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从html内容中解析锚链接./*我的HTML内容示例

I want to parse anchor link from the html content. /* My HTML Content Sample

<a class="productnamecolor colors_productname" href="http://www.cccxcxc.com/Nautical-Bubble-Romper-p/s15brpnt03.htm">*/
      <a class="productnamecolor colors_productname" href="http://www.dewewe.com/Nautical-Bubble-Romper-p/erewrwer.htm">
    <a class="productnamecolor colors_productname" href="http://www.sdsddsd.com/Nautical-Bubble-Romper-p/dsadadasd.htm"> 

*/锚点具有 href ,我想获取 Href 的值.但这给了我错误..

*/ The Anchor have href and i want to get the value of Href . But this is giving me error..

错误:单值上下文中的多值s.Attr()

package main

    import (
      "fmt"
      "log"

      "github.com/PuerkitoBio/goquery"
    )

    func ExampleScrape() {
      doc, err := goquery.NewDocument("http://www.myurl.com/category-s/1828.htm") 
      if err != nil {
        log.Fatal(err)
      }

    /* **my sample html after http open** <a class="productnamecolor colors_productname" href="http://www.cccxcxc.com/Nautical-Bubble-Romper-p/s15brpnt03.htm">*/
      <a class="productnamecolor colors_productname" href="http://www.dewewe.com/Nautical-Bubble-Romper-p/erewrwer.htm">
    <a class="productnamecolor colors_productname" href="http://www.sdsddsd.com/Nautical-Bubble-Romper-p/dsadadasd.htm"> ***/

    doc.Find("table.v65-productDisplay a.productnamecolor").Each(func(i int, s *goquery.Selection) {
        band := s.Attr("href") // here i want to get attribute " href " value. this is not working here.
        fmt.Printf(band)
      })
    }

    func main() {
      ExampleScrape()
    }

推荐答案

<代码> Selection.Attr 返回两个值:属性值和一个布尔值,指示该属性是否存在(如果为false,则该属性值为空).

Selection.Attr returns two values: the attribute value, and a boolean stating whether the attribute existed or not (the attribute value will be the empty if this is false).

当您忽略多个返回值时,Go不喜欢它,因此您必须将代码更改为以下内容:

Go doesn't like it when you ignore multiple return values, so you'll have to change your code to the following:

doc.Find("table.v65-productDisplay a.productnamecolor").Each(func(i int, s *goquery.Selection) {
    band, ok := s.Attr("href")
    if ok {
        fmt.Printf(band)
    }
})

这篇关于如何在Go语言中获取属性href值的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆