0

我需要使用 goquery 查找表的元素,就像我做 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()))
})}

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

4

1 回答 1

0

我已经通过 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()
}
于 2020-05-15T11:38:35.473 回答