go - 如何使用GoQuery查找具有特定ID的元素

标签 go goquery

我需要用goquery查找表的get元素,就像我用jquery那样:

$("#ctl00_cphBody_gvDebtors").find("td").each(function(index){
   if(index != 0){
       console.log($.trim($(this).text()))
}});

我通过client.PostForm收到响应,但是不重要。

使用goquery我尝试通过以下方式做到这一点:
doc.Find("#ctl00_cphBody_gvDebtors").Find("td").Each(func(i int, s *goquery.Selection) {
    fmt.Println(strings.TrimSpace(s.Text()))
})}

但是我什么也没得到。节点数组为空。我究竟做错了什么?

最佳答案

我已经直接通过Response.Body而不是通过其他结构字段传递了它,并且有效。
但是,此程序包(“github.com/PuerkitoBio/goquery”)不是jQuery。尽管它很棒,但是应该区别对待。我对作者的建议是对应该如何形成选择器添加良好的描述。好厉害!因为现在您不想了解正在发生的事情,而是深入研究代码以查找痛苦的根源!听我说!但是包装很棒!伟大而努力!我的例子如下。它已经在go.test中进行了测试,因此那里有语法,但是在我看来,这个想法很明确。我对此表示感谢。

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

func Example() {    
    var clientRequest = &http.Client{
        Timeout: 3 * time.Second,
        Transport: &http.Transport{
            TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
        }}
    response, err := clientRequest.PostForm(serviceURL, reqBody)

    doc, err := goquery.NewDocumentFromReader(response.Body)

    if err != nil {
        t.Fatal(err)
    }
    var person []string

    j := 0
/* this wonderful package is searching into depth so be sure that your every HTML element you search for has the same selector.
For Example if I've been doing it like that doc.Find("#ctl00_cphBody_gvDebtors")
There would be only one iteration into Each and this will be the String containing all the info
into this selector on the overhand example below contains each of td value of the table
And that's wonderful. If I was the creator of the package I would write it down in the documentation more precisely, cause now, no offense, it sucks!..*/

    doc.Find("#yourId td").Each(func(i int, s *goquery.Selection) {
// I don't want the first string into my array, so I filter it
        if j != 0 {
            person = append(person, strings.TrimSpace(s.Text()))
            }
        j++
    })

    fmt.Println(len(person))
}

func main(){
    Example()
}

关于go - 如何使用GoQuery查找具有特定ID的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61795268/

相关文章:

goquery- 将标签与后面的标签连接起来

goquery:到达另一个元素时停止解析

go - 我可以在一个 go 模块中包含多个包吗?如何?

html - 使用 goQuery 按 id 搜索标签

go - 在 Go 中传递文件指针

go - 从 golang 运行 cqlsh shell 命令

http - GoQuery 响应代码

html - 如何使用 golang 将 HTML 表格转换为数组

http - 使用计算键去构造

google-app-engine - 使用go在应用程序引擎中包含电子邮件 header ?