gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 03:20:26 27 4
gpt4 key购买 nike

为什么下面的测试会失败?

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])
}
}

这是测试结果:

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

换句话说,如果我无法预测第一个子元素是什么类型的 html 元素,我如何才能检索到第一个子元素的完整 HTML?

最佳答案

你要的其实是外层HTML,调用goquery.OuterHTML就可以得到功能。根据文档:

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).

所以只需将行更改为:

html, _ := goquery.OuterHTML(s)

关于go - 如何使用 goquery 检索子元素的完整 HTML?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54841662/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com