首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用goquery查找具有特定id的元素

如何使用goquery查找具有特定id的元素
EN

Stack Overflow用户
提问于 2020-05-14 18:39:44
回答 1查看 943关注 0票数 0

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

代码语言:javascript
复制
$("#ctl00_cphBody_gvDebtors").find("td").each(function(index){
   if(index != 0){
       console.log($.trim($(this).text()))
}});

我在client.PostForm上收到了回复,但我觉得这无关紧要。

对于goquery,我尝试这样做:

代码语言:javascript
复制
doc.Find("#ctl00_cphBody_gvDebtors").Find("td").Each(func(i int, s *goquery.Selection) {
    fmt.Println(strings.TrimSpace(s.Text()))
})}

但我什么也得不到。节点数组为空。我做错了什么?

EN

回答 1

Stack Overflow用户

发布于 2020-05-15 19:38:35

我直接传递了Response.Body,而不是通过其他结构字段,它起作用了。但是,这个包(“github.com/PuerkitoBio/goquery”)不是jQuery。虽然它很棒,但应该有不同的对待。我对作者的建议是添加关于选择器应该如何形成的良好描述。这真是太激烈了!因为现在要理解发生了什么,你并不想要,而是潜入代码中去寻找痛苦的根源!听我说完!但是这个包太棒了!伟大而努力的工作!下面是我的例子。它在go.test中进行了测试,因此有语法,但在我看来,它的想法是明确的。如果您能对此发表意见,我将不胜感激。

代码语言:javascript
复制
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()
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61795268

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档