dream752614590 2019-03-04 15:40
浏览 41
已采纳

如何找出选择器在第一个还是最后一个位置

I use goquery's function .Each() to recurse into the child elements. Is there a way to find out if this is the first (or last) child of a parent? I try to remove starting and trailing whitespace of HTML nodes. Checking for the first child is probably a matter of testing i == 0. But what about the last child element?

This is my code so far:

package main

import (
    "fmt"
    "io"
    "os"
    "strings"

    "github.com/PuerkitoBio/goquery"
)

// recursive function
func dumpElement(i int, sel *goquery.Selection) {
    fmt.Println("dump Element - is this the first or last element? I don't know")
    sel.Contents().Each(dumpElement)
}

func startRecursion(r io.Reader) error {
    g, err := goquery.NewDocumentFromReader(r)
    if err != nil {
        return err
    }

    g.Find(":root > body").Each(dumpElement)
    return nil
}

func main() {
    doc := `<!DOCTYPE html>
    <html><head><title>foo</title></head><body>
    <div class="bla">foo <b> bar </b> baz</div>
    </body></html>`

    if err := startRecursion(strings.NewReader(doc)); err != nil {
        os.Exit(-1)
    }
}
  • 写回答

1条回答 默认 最新

  • dsiftnc99059 2019-03-04 18:45
    关注

    Most likely you'd have to write a function that returns the funciton you are using, so you get access to the original selections length, something like:

    type iterator func(int, *goquery.Selection)
    
    func dumpElementFrom(s *goquery.Selection) iterator {
        lastIndex := s.Size() - 1
        return func(i int, sel *goquery.Selection) {
            if i == lastIndex {
                fmt.Println("Last Element")
            }
            sel.Contents().Each(dumpElement)
        }
    }
    
    
    func startRecursion(r io.Reader) error {
        g, err := goquery.NewDocumentFromReader(r)
        if err != nil {
            return err
        }
    
        g.Find(":root > body").Each(dumpElementFrom(g))
        return nil
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog