【问题标题】:How to compare HTML markup in Golang?如何比较 Golang 中的 HTML 标记?
【发布时间】:2016-05-28 11:48:38
【问题描述】:

我正在尝试开发一个测试套件,它可以检查 HTML 片段/文件在规范上是等价的。我很惊讶地发现,如果我解析相同的字符串或文件,https://godoc.org/golang.org/x/net/html#Node 会比较不同。我错过了什么?

希望这能说明问题:

package main

import (
    "fmt"
    "strings"

    "golang.org/x/net/html"
)

func main() {
    s := `<h1>
    test
    </h1><p>foo</p>`
    // s2 := `<h1>test</h1><p>foo</p>`

    doc, _ := html.Parse(strings.NewReader(s))
    doc2, _ := html.Parse(strings.NewReader(s))

    if doc == doc2 {
        fmt.Println("HTML is the same") // Expected this
    } else {
        fmt.Println("HTML is not the same") // Got this
    }
}

HTML 不一样

【问题讨论】:

标签: html go canonicalization


【解决方案1】:

最简单的方法是使用反射,因为html.Parse 返回*Node 对象。在 Go 中比较两个对象需要 reflect.DeepEqual

if reflect.DeepEqual(doc, doc2) {                                     
        fmt.Println("HTML is the same") 
} else {
        fmt.Println("HTML is not the same")                         
}

这会打印出“HTML 是一样的”。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2016-03-26
  • 2022-01-24
  • 2018-05-22
  • 2015-06-12
  • 1970-01-01
  • 2017-10-11
  • 2015-03-01
  • 2016-04-05
相关资源
最近更新 更多