doujiu4643 2015-01-14 00:15
浏览 98
已采纳

使用goquery查找其值包含空格的类

Answered. User PuerkitoBio helped me out with his goquery package, and I'm sure I won't be the only one wondering how to do this. (I can mark this question as 'answered' in two days)

When using goquery to find classes of html tags, I hit a problem when the class contains whitespace. Here's an example:

package main

import (
    "fmt"
    "github.com/PuerkitoBio/goquery"
    "strings"
)

func main() {
    html_code := strings.NewReader(`
<html>
    <body>
        <h1>
            <span class="text title">Go </span>
        </h1>
        <p>
            <span class="text">totally </span>
            <span class="post">kicks </span>
        </p>
        <p>
            <span class="text">hacks </span>
        </p>
    </body>
<html>
    `)
    doc, _ := goquery.NewDocumentFromReader(html_code)
}

If I want to find the class "text title", I thought I would do this:

doc.Find(".text title").Each(func(i int, s *goquery.Selection) {
    class, _ := s.Attr("class")
    fmt.Println(class, s.Text())
})

But this doesn't work. (Answer is below.)

  • 写回答

1条回答 默认 最新

  • duan0708676887 2015-01-14 00:19
    关注

    It was a problem with my understanding of HTML. The whitespace inside class="text title" shows that class has two values: text and title. In order to find multiple attributes of a class with goquery, I need to put them side by side (without whitespace) and prefix them with a .. Like this:

    doc.Find(".text.title").Each(func(i int, s *goquery.Selection) {
        class, _ := s.Attr("class")
        fmt.Println(class, s.Text())
    })
    

    Or if I ever want to find only the classes with the value title, I would do this:

    doc.Find(".title").Each(func(i int, s *goquery.Selection) {
        class, _ := s.Attr("class")
        fmt.Println(class, s.Text())
    })
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源