dosi8657
dosi8657
2019-02-23 12:34

如何使用goquery检索子元素的完整HTML?

  • IT行业问题
  • 计算机技术
  • it技术
  • 编程语言问答
  • 互联网问答
已采纳

Why does the following test fail?

func TestGetFirstElementHtml(t *testing.T) {
    test := `<speak><p>My paragraph</p></speak>`
    doc, _ := goquery.NewDocumentFromReader(strings.NewReader(test))
    var childrenHtml []string
    doc.Find("speak").Children().Each(func(i int, s *goquery.Selection) {
        html, _ := s.Html()
        childrenHtml = append(childrenHtml, html)
    })
    if childrenHtml[0] != "<p>My paragraph</p>" {
        t.Fatalf("First element html is not valid: '%s'", childrenHtml[0])
    }
}

This is the test result:

=== FAIL: . TestGetFirstElementHtml (0.00s)
    main_test.go:45: First element html is not valid: 'My paragraph'

In other words, how can I retrieve the full HTML of the first child of given that I cannot predict what kind html element that child is?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

1条回答

  • doucaishi0077 doucaishi0077 2年前

    What you want is actually outer HTML, and you can get it by calling goquery.OuterHTML function. As per document:

    func OuterHtml(s *Selection) (string, error)
    

    OuterHtml returns the outer HTML rendering of the first item in the selection - that is, the HTML including the first element's tag and attributes.

    Unlike InnerHtml, this is a function and not a method on the Selection, because this is not a jQuery method (in javascript-land, this is a property provided by the DOM).

    So just change the line to:

    html, _ := goquery.OuterHTML(s)
    
    点赞 评论 复制链接分享

为你推荐