登录
首页 >  Golang >  Go问答

无法被html.Parse() 解析的HTML格式

来源:stackoverflow

时间:2024-03-29 13:48:31 386浏览 收藏

小伙伴们有没有觉得学习Golang很有意思?有意思就对了!今天就给大家带来《无法被html.Parse() 解析的HTML格式》,以下内容将会涉及到,若是在学习中对其中部分知识点有疑问,或许看了本文就能帮到你!

问题内容

我正在编写一个 go 函数来读取 html 响应正文并提取页面标题。总的来说,该函数工作得很好,但我想测试响应正文根本不是正确 html 的代码路径。我为单元测试创​​建一些无效 html 的简单尝试已经失败。

显然,根据 html.parse 文档,这是因为:

html5 解析算法 [...] 非常复杂。生成的树可以包含隐式创建的节点,这些节点在 r 的数据中没有列出显式 ,并且节点的父节点可能与起始和结束 s 的简单处理所隐含的嵌套不同。相反,r 数据中的显式 s 可以被静默删除,而生成的树中没有相应的节点。

这里有一些代码演示了我一直在采取的方法:

https://play.golang.org/p/t5wjdtjncqq

package main

import (
    "bytes"
    "fmt"
    "golang.org/x/net/html"
)

func main() {
    inputs := []string{ "",
        "~",
        "<",
        "",
        "<",
        "",
        "<html><title>the c progr",
        "<html><title>the c programming language",
        "<html><title>the c programming language<",
        "<html><title>the c programming language</",
        "<html><title>the c programming language</ti",
        "<html><title>the c programming language</title",
        "<html><title>the c programming language",
        "the c programming language<",
        "the c programming languagethe c programming languagethe c programming languagethe c programming language",
    }

    for _, in := range inputs {
        fmt.printf("%s\n", in)

        r := bytes.newreader([]byte(in))
        _, err := html.parse(r)
        if err != nil {
            fmt.printf("could not parse html\n")
            panic(err)
        }
    }
}

愚蠢的我,我本以为其中许多会产生错误,因为从表面上看它们是无效的 html,但上面的代码在没有 panic'ing 的情况下遍历所有输入字符串——也就是说,没有非-来自 html.parse()nil err

我想我很感激一个宽松/宽容的 html 解析器,但是:有没有人有一个在输入 go 的 html.parse() 时会产生错误的文本示例?

编辑 1

结合 ferrybig 和 creationtribe 评论中的想法,我什至尝试了巨大的随机字节流:

rand.Seed(time.Now().UnixNano())

    in := make([]byte, 0)
    for i := 0; i < 2147483647; i++ {
        in = append(in, byte(rand.Intn(255)))
    }
    fmt.Printf("len(in) : %d\n", len(in))

    r := bytes.NewReader(in)
    _, err := html.Parse(r)

...仍然没有错误。

是否没有输入会导致html.parse()出错?


解决方案


快速阅读https://github.com/golang/net/blob/master/html/token.go,似乎唯一返回的错误可能是:

  • 一旦 r 完全读取成功,io.eof;
  • 底层 io.reader 返回的任何其他错误;或
  • html.errbufferexceeded

在初次读取后如何触发 errbufferexceeded 对我来说并不明显,但您可以通过提供虚拟读取器来触发 html.parse 的错误:

type ErrReader struct { Error error }

func (e *ErrReader) Read([]byte) (int, error) {
    return nil, e.Error
}

https://play.golang.org/p/s78HpfMLAI8

希望有帮助

终于介绍完啦!小伙伴们,这篇关于《无法被html.Parse() 解析的HTML格式》的介绍应该让你收获多多了吧!欢迎大家收藏或分享给更多需要学习的朋友吧~golang学习网公众号也会发布Golang相关知识,快来关注吧!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>